Description
model_dump(exclude_unset=True) on a model containing a Union field produces spurious PydanticSerializationUnexpectedValue warnings when a union member has unset fields with defaults.
Reproduction
from typing import Literal
from pydantic import BaseModel
class Cat(BaseModel):
type: Literal['cat']
color: str | None = None # field with default
class Dog(BaseModel):
type: Literal['dog']
class Zoo(BaseModel):
animals: list[Cat | Dog]
cat = Cat(type='cat')
zoo = Zoo(animals=[cat])
# Sanity check: model_dump without exclude_unset works fine
assert zoo.model_dump() == {'animals': [{'type': 'cat', 'color': None}]}
# Sanity check: model_dump(exclude_unset=True) on the Cat alone works fine
assert cat.model_dump(exclude_unset=True) == {'type': 'cat'}
# BUG: model_dump(exclude_unset=True) on the parent Zoo produces warnings
assert zoo.model_dump(exclude_unset=True) == {'animals': [{'type': 'cat'}]}
The last line produces:
UserWarning: Pydantic serializer warnings:
PydanticSerializationUnexpectedValue(Expected 2 fields but got 1: Expected `Cat` - serialized value may not be as expected [field_name='animals', ...])
PydanticSerializationUnexpectedValue(Expected `Dog` - serialized value may not be as expected [field_name='animals', ...])
The output is correct, but the warnings are spurious.
Version info
- Broken: pydantic 2.13.0b2 / pydantic-core 2.42.0 (installed from latest on github)
- Works: pydantic 2.12.5 / pydantic-core 2.41.5
- Python 3.12
Description
model_dump(exclude_unset=True)on a model containing aUnionfield produces spuriousPydanticSerializationUnexpectedValuewarnings when a union member has unset fields with defaults.Reproduction
The last line produces:
The output is correct, but the warnings are spurious.
Version info