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

Handle non-json native enum values #7056

Merged
merged 2 commits into from Aug 16, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions pydantic/json_schema.py
Expand Up @@ -676,6 +676,8 @@ def literal_schema(self, schema: core_schema.LiteralSchema) -> JsonSchemaValue:
The generated JSON schema.
"""
expected = [v.value if isinstance(v, Enum) else v for v in schema['expected']]
# jsonify the expected values
expected = [to_jsonable_python(v) for v in expected]

if len(expected) == 1:
return {'const': expected[0]}
Expand Down
13 changes: 13 additions & 0 deletions tests/test_json_schema.py
Expand Up @@ -5384,3 +5384,16 @@ class MyDataclass:
json_schema = adapter.json_schema()
for key in 'abcdef':
assert json_schema['properties'][key] == {'title': key.upper(), 'type': 'integer'} # default is not present


def test_enum_complex_value() -> None:
"""https://github.com/pydantic/pydantic/issues/7045"""

class MyEnum(Enum):
foo = (1, 2)
bar = (2, 3)

ta = TypeAdapter(MyEnum)

# insert_assert(ta.json_schema())
assert ta.json_schema() == {'enum': [[1, 2], [2, 3]], 'title': 'MyEnum', 'type': 'array'}
Copy link
Contributor

@Viicos Viicos Aug 9, 2023

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

Copy link
Member Author

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

Copy link
Contributor

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.