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
Literal enum fields are stored as mix-in type instead of enum field when using parse_raw or parse_json #2166
Comments
Hi @yobiscus def make_literal_validator(type_: Any) -> Callable[[Any], Any]:
permitted_choices = all_literal_values(type_)
- allowed_choices_set = set(permitted_choices)
def literal_validator(v: Any) -> Any:
- if v not in allowed_choices_set:
+ for x in permitted_choices:
+ if x == v:
+ return x
+ else:
raise errors.WrongConstantError(given=v, permitted=permitted_choices)
- return v
return literal_validator to return the original value in |
I see, thanks. This now makes sense given the logic. Now that I've had time to digest this some more, I feel like this is a bug in Pydantic (especially because the field is identified by mypy as an enum field rather than a string). Do you think any other types are subject to this issue? My guess is that this behaviour is unusual and specific to Enums because I would be happy to look more closely at a solution for this problem, but I am worried about breaking backwards compatibility in a 1.X release, so I'm also wondering what the recommended direction is for this issue. |
Hi @yobiscus |
Thanks for reporting this, it's definitely a bug. Another example would be I think @PrettyWood's solutions in #2181 is pretty good. |
Checks
Feature Request
Output of
python -c "import pydantic.utils; print(pydantic.utils.version_info())"
:I was expecting that the Pydantic would store
Bar.FIZ
for theLiteral[Bar.FIZ]
field above, as opposed to storing astr
type (the enum's mix-in type. Mypy flagsLiteral[Bar.FIZ]
above as an enum field, so accessingvalue
on thebarfiz
attribute, for example, is perfectly fine by Mypy's rules, but breaks during runtime.I realize that mypy's support for Literal enum fields is relatively new, but they have interesting properties that I am looking to make use of (I would love to see this work with discriminated union types, for example).
Would you consider adding a Config field to enable this behaviour? Should this be flagged as a bug instead and targetted for a 2.0 release?
Possibly related bugs:
The text was updated successfully, but these errors were encountered: