Essential Marshmallow - Nested post_load behaviour
nested_and_load.py
:
from typing import Any
from marshmallow import Schema
from marshmallow import fields
from marshmallow import post_load
def evlove(val, type_):
if type_ == 'int':
return int(val)
if type_ == 'float':
return float(val)
if type_ == 'str':
return str(val)
class DynamicYYDS(Schema):
value = fields.String()
type = fields.String()
@post_load
def evlove(self, data, **kw) -> Any:
return evlove(data['value'], data['type'])
class Nested(Schema):
name = fields.String()
value = fields.Nested(DynamicYYDS)
@post_load
def mapping(self, data, **kw):
# marshmallow.exceptions.ValidationError: {'_schema': ['Invalid input type.']}
# return {data['name']: DynamicYYDS().load(data['value'])}
return {data['name']: data['value']}
if __name__ == '__main__':
# First Level
print(123 == DynamicYYDS().load({'value': '123', 'type': "int"}))
print('abc' == DynamicYYDS().load({'value': 'abc', 'type': "str"}))
print(3.1415 == DynamicYYDS().load({'value': '3.1415', 'type': "float"}))
# Nested
print({'foo': 123} == Nested().load({"name": "foo",
"value": {"value": "123",
"type": "int"}}))
print({'bar': 'abc'} == Nested().load({'name': 'bar',
'value': {'value': 'abc',
'type': 'str'}}))
print( {'spam': 3.1415} == Nested().load({'name': 'spam',
'value': {'value': '3.1415',
'type': 'float'}}))
$ python nested_and_load.py
True
True
True
True
True
True