Serialization of unions picks the wrong member when a default's type is not an exact match for the type annotation
Author: stanmartCreated Jul 29, 2025Updated Sep 27, 2026
Labelstopic-serializationbug V2topic-unions
Initial Checks
- I confirm that I'm using Pydantic V2
Description
When serializing a pydantic model that contains the union of other pydantic models as a field, the incorrect model can be used for serialization when one has a default value that is not an exact match for its annotation (please see example).
The problem goes away if
- The
Parent's default is defined asa: float = 0.0(default literal is an exact match for the annotation) ais supplied explicitly when theChildis initialized- The unioned classes don't inherit from each other
validate_defaultis set toTrue
Normally I'd say that the defaults not conforming to the type annotation is an user error, but I think this one should be considered as bug given that (1) according to PEP 484, when an argument is annotated as having type float, an argument of type int is acceptable and (2) this behavior does not happen in similar cases (e.g., when using a TypeAdapter or without inheritance) and leads to silent serialization errors.
Example Code
from pydantic import BaseModel
class Parent(BaseModel):
a: float = 0
class Child(Parent):
b: int
class Container(BaseModel):
union: Parent | Child
container = Container(
union=Child(
b=3,
),
)
print(container.model_dump_json(indent=2))
# {
# "union": {
# "a": 0.0
# }
# }Python, Pydantic & OS Version
pydantic version: 2.11.7
pydantic-core version: 2.33.2
pydantic-core build: profile=release pgo=false
python version: 3.13.5 | packaged by conda-forge | (main, Jun 16 2025, 08:24:05) [Clang 18.1.8 ]
platform: macOS-15.5-arm64-arm-64bit-Mach-O
related packages: typing_extensions-4.14.1 fastapi-0.115.14 mypy-1.17.0 pydantic-settings-2.10.1
commit: unknownSource: pydantic/pydantic