Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validating enum type #244

Open
zedrdave opened this issue Jun 22, 2023 · 1 comment
Open

Validating enum type #244

zedrdave opened this issue Jun 22, 2023 · 1 comment

Comments

@zedrdave
Copy link

zedrdave commented Jun 22, 2023

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.

@cbreins
Copy link

cbreins commented Oct 30, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants