lovasoa / marshmallow_dataclass

Automatic generation of marshmallow schemas from dataclasses.

Home Page:https://lovasoa.github.io/marshmallow_dataclass/html/marshmallow_dataclass.html

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Validating enum type

zedrdave opened this issue · comments

commented

I have installed marshmallow-dataclass[enum,union] as per the instructions.

But when I try to validate a dataclass using an Enum/EnumField type, the validation fails.

Using marshmallow Schema directly works:

from dataclasses import dataclass
from enum import Enum
from marshmallow import Schema
from marshmallow_enum import EnumField
import marshmallow_dataclass

class RuleSchema(Schema):
    class Action(Enum):
        READ = "read"
        WRITE = "write"
    action = EnumField(Action, by_value=True)

# Works
print(RuleSchema().validate({"action": RuleSchema.Action.READ}))

Using marshmallow_dataclass.class_schema fails:

@dataclass
class Rule:
    class Action(Enum):
        READ = "read"
        WRITE = "write"
    action: Action = EnumField(Action, by_value=True)
    
# outputs as expected: {'action': 'READ'} 
print(marshmallow_dataclass.class_schema(Rule)().dump({"action": Rule.Action.READ}))

# Fails validation with: {'action': ['Not a valid string.']}
print(marshmallow_dataclass.class_schema(Rule)().validate({"action": Rule.Action.READ}))

After looking through previous issues and code and seeing mentions of the switch from marshmallow_enum to the native marshmallow type, I updated the code accordingly and still getting the same problem.

I came across the same problem and I am using a Literal type for now as a substitute. I don't know if that helps for your use case @zedrdave