Skip to content

Commit

Permalink
Fix discriminated union bug with unsubstituted type var (#9124)
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle committed Mar 27, 2024
1 parent 548feec commit 7ac7881
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pydantic/_internal/_generate_schema.py
Expand Up @@ -433,9 +433,9 @@ class CollectedInvalid(Exception):
def clean_schema(self, schema: CoreSchema) -> CoreSchema:
schema = self.collect_definitions(schema)
schema = simplify_schema_references(schema)
schema = _discriminated_union.apply_discriminators(schema)
if collect_invalid_schemas(schema):
raise self.CollectedInvalid()
schema = _discriminated_union.apply_discriminators(schema)
schema = validate_core_schema(schema)
return schema

Expand Down
26 changes: 26 additions & 0 deletions tests/test_discriminated_union.py
Expand Up @@ -2005,3 +2005,29 @@ class Root(TypedDict):

ta = TypeAdapter(Root)
assert ta.core_schema['fields']['data_class']['schema']['fields']['animal']['schema']['type'] == 'tagged-union'


def test_discriminated_union_with_unsubstituted_type_var() -> None:
T = TypeVar('T')

class Dog(BaseModel, Generic[T]):
type_: Literal['dog']
friends: List['GenericPet']
id: T

class Cat(BaseModel, Generic[T]):
type_: Literal['cat']
friends: List['GenericPet']
id: T

GenericPet = Annotated[Union[Dog[T], Cat[T]], Field(..., discriminator='type_')]

ta = TypeAdapter(Dog[int])
int_dog = {
'type_': 'dog',
'friends': [{'type_': 'dog', 'friends': [], 'id': 2}, {'type_': 'cat', 'friends': [], 'id': 3}],
'id': 1,
}
assert ta.validate_python(int_dog).id == 1
assert ta.validate_python(int_dog).friends[0].id == 2
assert ta.validate_python(int_dog).friends[1].id == 3

0 comments on commit 7ac7881

Please sign in to comment.