pydantic
pydantic copied to clipboard
Apply equivalent simplifications on annotations/core schemas
Initial Checks
- [x] I confirm that I'm using Pydantic V2
Description
E.g. in this case, a simplification could be made. As it stands, the propertyNames field is missing for the field2.
{
"properties": {
"field1": {
"additionalProperties": {
"type": "integer"
},
"propertyNames": {
"enum": [
"a",
"b"
]
},
"title": "Field1",
"type": "object"
},
"field2": {
"additionalProperties": {
"type": "integer"
},
"title": "Field2",
"type": "object"
}
},
"required": [
"field1",
"field2"
],
"title": "Foo",
"type": "object"
}
Example Code
from typing import Literal, Union
import pydantic
class Foo(pydantic.BaseModel):
field1: dict[Literal["a", "b"], int]
field2: dict[Union[Literal["a"], Literal["b"]], int]
print(Foo.model_json_schema())
Python, Pydantic & OS Version
pydantic version: 2.11.5
pydantic-core version: 2.33.2
pydantic-core build: profile=release pgo=false
python version: 3.13.4 (v3.13.4:8a526ec7cbe, Jun 3 2025, 21:14:54) [Clang 16.0.0 (clang-1600.0.26.6)]
platform: macOS-15.6.1-arm64-arm-64bit-Mach-O
related packages: typing_extensions-4.14.0 fastapi-0.115.12
commit: unknown
I expect this kind of things to happen in different scenarios as well. Two solutions could be used:
- Simplify at the annotation level (i.e. before generating the core schema, implement a bunch of simplifications such as
Union[Literal[<a1>], Literal[<a2>], ..., Literal[<an>]]->Literal[<a1>, <a2>, ..., <an>]) - Simplify at the core schema level (e.g.
{'type': 'union', 'choices': [{'type': 'literal', 'expected': ['a']}, {'type': 'literal', 'expected': ['b']}]}->{'type': 'literal', 'expected': ['a', 'b']}).
Low prio though, most of the times users should just use the simpler annotation form.