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
Handle non-json native enum values #7056
Conversation
please review |
Deploying with Cloudflare Pages
|
Thanks 🙏 this will raise an exception if the type can't be serialized using from enum import Enum
from pydantic_core import to_jsonable_python
class Test: pass
class A(Enum):
b = Test()
to_jsonable_python(A.b.value)
#> pydantic_core._pydantic_core.PydanticSerializationError: Unable to serialize unknown type: <__main__.Test object at 0x7fcad9baf070> But I guess it is expected? |
I guess so! Better than generating invalid json and having something downstream crash right? |
ta = TypeAdapter(MyEnum) | ||
|
||
# insert_assert(ta.json_schema()) | ||
assert ta.json_schema() == {'enum': [[1, 2], [2, 3]], 'title': 'MyEnum', 'type': 'array'} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This would still fail to parse with JSON data matching this schema:
TypeAdapter(Direction).validate_json('[0,1]')
#> Input should be (0, 1),(1, 1),(1, 0),(1, -1),(0, -1),(-1, -1),(-1, 0) or (-1, 1) [type=enum, input_value=[0, 1], input_type=list]
But serializing complex enums by their value isn't a good idea anyway, as I mentioned in #7045
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yup not much we can do about that
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it would work with an appropriate validator, perhaps annoying that you have to write it, but I think given how rare this is it's not unreasonable, and I think this change to the JSON schema generation is an improvement either way.
True! Just wanted to be sure pydantic "allowed" exceptions to be raised in this |
I think it should work to use the |
Fixes #7045
This isn't perfect, e.g. ideally if the value is always a two tuple of ints it would be reflected in the generated schema. But this is better than invalid json.
Selected Reviewer: @dmontagu