pydantic icon indicating copy to clipboard operation
pydantic copied to clipboard

Apply equivalent simplifications on annotations/core schemas

Open mglst opened this issue 3 months ago • 1 comments

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

mglst avatar Sep 17 '25 21:09 mglst

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.

Viicos avatar Sep 19 '25 14:09 Viicos