You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When using Enums with complex values, the generated JSON Schema is incorrect (e.g. this validator raises an error).
By the way, I'm trying to find a good way of serializing such enums (by their name), similar to #6466, but imho it it a bit cumbersome for a use case that could be pretty common. Do you think a helper could be integrated into Pydantic?
A (weird) alternative implementation (has the benefit of not having to subclass from a custom Enum class, as suggested in #6466):
fromtypingimportAnnotatedfrompydanticimportBaseModel, PlainSerializer, WrapValidatordefserialize_with_name(EnumClass: type[Enum]) ->type[Enum]:
returnAnnotated[
EnumClass,
WrapValidator(lambdav, handler: EnumClass[v] ifisinstance(v, str) elsehandler(v)),
PlainSerializer(lambdael: el.name, return_type=Literal[EnumClass._member_names_], when_used="json"), # The Literal is still valid Python
]
classModel(BaseModel):
direction: serialize_with_name(Direction)
I don't in principle have any objection to providing a way to serialize/validate enums by their name, but I think whether it would be accepted would depend a bit on the implementation. I suspect it could be done without too much hassle through a custom __get_pydantic_core_schema__ but I'm not sure.
I don't in principle have any objection to providing a way to serialize/validate enums by their name, but I think whether it would be accepted would depend a bit on the implementation. I suspect it could be done without too much hassle through a custom __get_pydantic_core_schema__ but I'm not sure.
Initial Checks
Description
When using Enums with complex values, the generated JSON Schema is incorrect (e.g. this validator raises an error).
By the way, I'm trying to find a good way of serializing such enums (by their name), similar to #6466, but imho it it a bit cumbersome for a use case that could be pretty common. Do you think a helper could be integrated into Pydantic?
A (weird) alternative implementation (has the benefit of not having to subclass from a custom
Enum
class, as suggested in #6466):Related issue: #3174
Example Code
Python, Pydantic & OS Version
Selected Assignee: @hramezani
The text was updated successfully, but these errors were encountered: