I'm having trouble using the attribute field of marshmallow dataclasses (v3.x).
My problem: I get the input keys for schema.load as dict with non-python-valid names e.g. "external.id" and I want the output keys with schema.dump to be different e.g. "externalId". So I need to load and dump with two different keys.
The data_key
is not enough, because it would dump it with the same naming. Using the attribute
key additionally, does not help.
My example code here:
import marshmallow_dataclass
from dataclasses import field
@marshmallow_dataclass.dataclass
class Uao:
externalId: str = field(metadata=dict(data_key="external.id", attribute="externalId"))
schema = marshmallow_dataclass.class_schema(Uao)
uao_loaded = schema().load({"external.id": "1234"})
uao_dumped = schema().dump(uao_loaded)
should return: {'externalId': '1234'}
but returns: {'external.id': '1234'}
What am I doing wrong? I already know, there is an old marshmallow version with load_from
and dump_to
where my requirement probably was possible - but it is no option to use an old version of the lib.
Also, it's not pythonic to write the instance attribute of the class in camelCase. I would prefer it to name it "external_id", but then it throws TypeError: __init__() got an unexpected keyword argument 'externalId'