Initial Checks
Description
During model construction, pydantic doesn't pull Tags from inner named type alias annotations, but will do it if the entire union is a named type alias, as seen in the example below.
Results in the following error:
PydanticUserError: `Tag` not provided for choice {'type': 'definition-ref', 'schema_ref': '__main__.TaggedApplePie:140478632382272'} used with `Discriminator`
Example Code
from typing import Annotated, Any, Literal
from pydantic import BaseModel, Discriminator, Tag
class Pie(BaseModel):
time_to_cook: int
num_ingredients: int
class ApplePie(Pie):
fruit: Literal['apple'] = 'apple'
class PumpkinPie(Pie):
filling: Literal['pumpkin'] = 'pumpkin'
def get_discriminator_value(v: Any) -> str:
print("I'm discriminating!")
if isinstance(v, dict):
return v.get('fruit', v.get('filling'))
return getattr(v, 'fruit', getattr(v, 'filling', None))
# This works
type Dessert = Annotated[
(Annotated[ApplePie, Tag('apple')] | Annotated[PumpkinPie, Tag('pumpkin')]),
Discriminator(get_discriminator_value),
]
class ThanksgivingDinner(BaseModel):
dessert: Dessert
# This doesn't work
# Works if using implicit alias: TaggedApplePie = Annotated[ApplePie, Tag('apple')]
type TaggedApplePie = Annotated[ApplePie, Tag('apple')]
class ThanksgivingDinnerSeconds(BaseModel):
dessert: Annotated[
(TaggedApplePie | Annotated[PumpkinPie, Tag('pumpkin')]),
Discriminator(get_discriminator_value),
]
Python, Pydantic & OS Version
pydantic version: 2.11.4
pydantic-core version: 2.33.2
pydantic-core build: profile=release pgo=false
python version: 3.12.9 | packaged by Anaconda, Inc. | (main, Feb 6 2025, 18:56:27) [GCC 11.2.0]
platform: Linux-5.4.0-172-generic-x86_64-with-glibc2.31
related packages: pydantic-extra-types-2.10.4 pydantic-settings-2.9.1 fastapi-0.115.12 typing_extensions-4.13.2
commit: unknown
Initial Checks
Description
During model construction, pydantic doesn't pull Tags from inner named type alias annotations, but will do it if the entire union is a named type alias, as seen in the example below.
Results in the following error:
Example Code
Python, Pydantic & OS Version