Skip to content

Validating enum type #244

Open
Open
@zedrdave

Description

@zedrdave

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions