lovasoa / marshmallow_dataclass

Automatic generation of marshmallow schemas from dataclasses.
https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html
MIT License
456 stars 78 forks source link

Enum fields always cast as JSON instead of native type #233

Open dgaedcke opened 1 year ago

dgaedcke commented 1 year ago

I'm using a combination of flask_smorest (swagger), native dataclasses and marshmallow_dataclass and I can't seem to figure out the syntax make the schema cast to and from native python Enum types when it updates my dataclass ... it always builds my payload at JsonObject instead of str (see below)

@BuiltValueField(wireName: r'sex1') JsonObject? get sex1;

Can you tell me what I'm doing wrong ... I've tried all the following:

@unique class Sex(IntEnum):

NEVERSET = 0
UNKNOWN = 1
FEMALE = 2
MALE = 3

`class _SexSerialized(fields.Field): """Field that serializes to a string of sex name"""

def _serialize(self: _SexSerialized, value: Sex, attr, obj, **kwargs) -> str:
    if value is None:
        return ""
    print("_SexSerialized:")
    print(type(value))
    return value.name

def _deserialize(self: _SexSerialized, value: str, attr, data, **kwargs) -> Sex:
    try:
        return Sex[value]
    except ValueError as error:
        raise ValidationError("Pin codes must contain only digits.") from error

def dump_default(self: _SexSerialized) -> Sex:
    return Sex.UNKNOWN

SexSerializedMsg = NewType("SexSerialized", Sex, field=fields.Enum)

@dataclass() class PersonRowMsg(): sex1: Sex = Sex.UNKNOWN sex2: _SexSerialized = field() sex3: SexSerializedMsg = field() `