Skip to content

联合类型

联合类型与 Pydantic 验证的所有其他类型有着根本性不同 —— 它不要求所有字段/项/值都有效,而只要求联合类型中的一个成员有效。

这导致验证联合类型存在一些细微差别:

  • 应该按何种顺序针对联合类型的哪些成员来验证数据?
  • 验证失败时应抛出哪些错误?

验证联合类型感觉像是为验证过程增加了一个正交维度。

为解决这些问题,Pydantic 支持三种验证联合类型的基本方法:

  1. 从左到右模式 - 最简单的方法,按顺序尝试联合类型的每个成员,返回第一个匹配项
  2. 智能模式 - 类似"从左到右模式",按顺序尝试成员;但验证会越过第一个匹配项以寻找更好的匹配,这是大多数联合验证的默认模式
  3. 可区分联合类型 - 基于区分符,仅尝试联合类型中的一个成员

Tip

通常,我们推荐使用可区分联合类型。与未标记的联合类型相比,它们不仅性能更高,而且更可预测,因为它们允许你控制要验证的联合成员。

对于复杂情况,如果使用未标记的联合类型,且需要对联合成员验证尝试顺序提供保证,建议使用 union_mode='left_to_right'

如果需要极其特殊的行为,可以使用自定义验证器

联合模式

从左到右模式

Note

由于此模式常导致意外的验证结果,它在 Pydantic >=2 中不是默认模式,而是默认使用 union_mode='smart'

采用此方法时,按定义顺序尝试针对联合类型的每个成员进行验证,并接受第一个成功的验证作为输入。

如果所有成员验证都失败,验证错误将包含联合类型所有成员的错误信息。

union_mode='left_to_right' 必须作为 Field 参数设置在要使用它的联合字段上。

Union with left to right mode
from typing import Union

from pydantic import BaseModel, Field, ValidationError


class User(BaseModel):
    id: Union[str, int] = Field(union_mode='left_to_right')


print(User(id=123))
#> id=123
print(User(id='hello'))
#> id='hello'

try:
    User(id=[])
except ValidationError as e:
    print(e)
    """
    2 validation errors for User
    id.str
      Input should be a valid string [type=string_type, input_value=[], input_type=list]
    id.int
      Input should be a valid integer [type=int_type, input_value=[], input_type=list]
    """
Union with left to right mode
from pydantic import BaseModel, Field, ValidationError


class User(BaseModel):
    id: str | int = Field(union_mode='left_to_right')


print(User(id=123))
#> id=123
print(User(id='hello'))
#> id='hello'

try:
    User(id=[])
except ValidationError as e:
    print(e)
    """
    2 validation errors for User
    id.str
      Input should be a valid string [type=string_type, input_value=[], input_type=list]
    id.int
      Input should be a valid integer [type=int_type, input_value=[], input_type=list]
    """

这种情况下成员的顺序非常重要,如下调整上述示例所示:

Union with left to right - unexpected results
from typing import Union

from pydantic import BaseModel, Field


class User(BaseModel):
    id: Union[int, str] = Field(union_mode='left_to_right')


print(User(id=123))  # (1)
#> id=123
print(User(id='456'))  # (2)
#> id=456
  1. 如预期,输入针对 int 成员验证,结果符合预期。
  2. 我们处于宽松模式,数字字符串 '123' 对联合的第一个成员 int 是有效输入。 由于首先尝试该成员,我们得到了 idint 而非 str 的意外结果。
Union with left to right - unexpected results
from pydantic import BaseModel, Field


class User(BaseModel):
    id: int | str = Field(union_mode='left_to_right')


print(User(id=123))  # (1)
#> id=123
print(User(id='456'))  # (2)
#> id=456
  1. 如预期,输入针对 int 成员验证,结果符合预期。
  2. 我们处于宽松模式,数字字符串 '123' 对联合的第一个成员 int 是有效输入。 由于首先尝试该成员,我们得到了 idint 而非 str 的意外结果。

智能模式

由于 union_mode='left_to_right' 可能产生意外结果,在 Pydantic >=2 中,Union 验证的默认模式是 union_mode='smart'

在此模式下,pydantic 尝试从联合成员中选择与输入最匹配的项。具体算法可能在 Pydantic 次要版本间变更,以改进性能和准确性。

Note

我们保留在未来 Pydantic 版本中调整内部 smart 匹配算法的权利。如果依赖非常特定的匹配行为,建议使用 union_mode='left_to_right'可区分联合类型

智能模式算法

智能模式算法使用两个指标来确定输入的最佳匹配:

  1. 设置的有效字段数(与模型、数据类和类型化字典相关)
  2. 匹配的精确度(与所有类型相关)

设置的有效字段数

Note

此指标在 Pydantic v2.8.0 中引入。在此版本之前,仅使用精确度来确定最佳匹配。

此指标目前仅与模型、数据类和类型化字典相关。

设置的有效字段数越多,匹配越好。嵌套模型上设置的字段数也会被考虑。 这些计数向上冒泡到顶级联合,其中具有最高计数的联合成员被视为最佳匹配。

对于此指标相关的数据类型,我们优先考虑此计数而非精确度。对于所有其他类型,我们仅使用精确度。

精确度

对于 exactness,Pydantic 将联合成员的匹配评分到以下三组之一(从最高分到最低分):

  • 精确类型匹配,例如将 int 输入验证到 float | int 联合时,对 int 成员是精确类型匹配
  • 严格模式下验证会成功
  • 在宽松模式下验证会成功

产生最高精确度得分的联合匹配将被视为最佳匹配。

在智能模式下,采取以下步骤尝试选择输入的最佳匹配:

  1. 从左到右尝试联合成员,任何成功的匹配按上述三个精确度类别之一评分,同时统计有效字段设置计数。
  2. 评估所有成员后,返回具有最高“有效字段设置”计数的成员。
  3. 如果最高“有效字段设置”计数出现平局,则使用精确度得分作为决胜局,返回具有最高精确度得分的成员。
  4. 如果所有成员验证都失败,返回所有错误。
  1. 从左到右尝试联合成员,任何成功的匹配按上述三个精确度类别之一评分。
    • 如果验证成功且为精确类型匹配,则立即返回该成员,且不会尝试后续成员。
  2. 如果至少有一个成员以“严格”匹配成功,返回最左侧的“严格”匹配。
  3. 如果至少有一个成员在“宽松”模式下验证成功,返回最左侧的匹配。
  4. 所有成员验证都失败,返回所有错误。
from typing import Union
from uuid import UUID

from pydantic import BaseModel


class User(BaseModel):
    id: Union[int, str, UUID]
    name: str


user_01 = User(id=123, name='John Doe')
print(user_01)
#> id=123 name='John Doe'
print(user_01.id)
#> 123
user_02 = User(id='1234', name='John Doe')
print(user_02)
#> id='1234' name='John Doe'
print(user_02.id)
#> 1234
user_03_uuid = UUID('cf57432e-809e-4353-adbd-9d5c0d733868')
user_03 = User(id=user_03_uuid, name='John Doe')
print(user_03)
#> id=UUID('cf57432e-809e-4353-adbd-9d5c0d733868') name='John Doe'
print(user_03.id)
#> cf57432e-809e-4353-adbd-9d5c0d733868
print(user_03_uuid.int)
#> 275603287559914445491632874575877060712
from uuid import UUID

from pydantic import BaseModel


class User(BaseModel):
    id: int | str | UUID
    name: str


user_01 = User(id=123, name='John Doe')
print(user_01)
#> id=123 name='John Doe'
print(user_01.id)
#> 123
user_02 = User(id='1234', name='John Doe')
print(user_02)
#> id='1234' name='John Doe'
print(user_02.id)
#> 1234
user_03_uuid = UUID('cf57432e-809e-4353-adbd-9d5c0d733868')
user_03 = User(id=user_03_uuid, name='John Doe')
print(user_03)
#> id=UUID('cf57432e-809e-4353-adbd-9d5c0d733868') name='John Doe'
print(user_03.id)
#> cf57432e-809e-4353-adbd-9d5c0d733868
print(user_03_uuid.int)
#> 275603287559914445491632874575877060712

可区分联合类型

可区分联合类型有时称为“标记联合类型”。

我们可以使用可区分联合类型来更高效地验证 Union 类型,通过选择要验证的联合成员。

这使得验证更高效,并避免验证失败时错误激增。

向联合添加区分符还意味着生成的 JSON 模式实现了相关的 OpenAPI 规范

使用 str 区分符的可区分联合类型

通常,在具有多个模型的 Union 情况下,所有联合成员都有一个共同字段,可用于区分数据应针对哪个联合情况进行验证;这在 OpenAPI 中称为“区分符”。

要根据该信息验证模型,你可以在每个模型中设置相同的字段 —— 我们称之为 my_discriminator —— 并赋予一个(或多个)Literal 值作为区分值。 对于你的 Union,你可以在其值中设置区分符:Field(discriminator='my_discriminator')

from typing import Literal, Union

from pydantic import BaseModel, Field, ValidationError


class Cat(BaseModel):
    pet_type: Literal['cat']
    meows: int


class Dog(BaseModel):
    pet_type: Literal['dog']
    barks: float


class Lizard(BaseModel):
    pet_type: Literal['reptile', 'lizard']
    scales: bool


class Model(BaseModel):
    pet: Union[Cat, Dog, Lizard] = Field(discriminator='pet_type')
    n: int


print(Model(pet={'pet_type': 'dog', 'barks': 3.14}, n=1))
#> pet=Dog(pet_type='dog', barks=3.14) n=1
try:
    Model(pet={'pet_type': 'dog'}, n=1)
except ValidationError as e:
    print(e)
    """
    1 validation error for Model
    pet.dog.barks
      Field required [type=missing, input_value={'pet_type': 'dog'}, input_type=dict]
    """
from typing import Literal

from pydantic import BaseModel, Field, ValidationError


class Cat(BaseModel):
    pet_type: Literal['cat']
    meows: int


class Dog(BaseModel):
    pet_type: Literal['dog']
    barks: float


class Lizard(BaseModel):
    pet_type: Literal['reptile', 'lizard']
    scales: bool


class Model(BaseModel):
    pet: Cat | Dog | Lizard = Field(discriminator='pet_type')
    n: int


print(Model(pet={'pet_type': 'dog', 'barks': 3.14}, n=1))
#> pet=Dog(pet_type='dog', barks=3.14) n=1
try:
    Model(pet={'pet_type': 'dog'}, n=1)
except ValidationError as e:
    print(e)
    """
    1 validation error for Model
    pet.dog.barks
      Field required [type=missing, input_value={'pet_type': 'dog'}, input_type=dict]
    """

使用可调用 Discriminator 的可区分联合类型

API 文档

pydantic.types.Discriminator

在具有多个模型的 Union 情况下,有时并没有一个统一的字段 across 所有模型可用作区分符。 这正是可调用 Discriminator 的完美用例。

Tip

设计可调用区分符时,请记住可能需要处理 dict 和模型类型输入。这种模式类似于 mode='before' 验证器,需要预期各种形式的输入。

但是等等!你会问,我只预期传入 dict 类型,为什么需要处理模型? Pydantic 在序列化时也会使用可调用区分符,此时输入到你的可调用对象很可能是模型实例。

在以下示例中,你将看到可调用区分符被设计为处理 dict 和模型输入。 如果不遵循此实践,最好情况是在序列化期间收到警告,最坏情况是在验证期间出现运行时错误。

from typing import Annotated, Any, Literal, Union

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:
    if isinstance(v, dict):
        return v.get('fruit', v.get('filling'))
    return getattr(v, 'fruit', getattr(v, 'filling', None))


class ThanksgivingDinner(BaseModel):
    dessert: Annotated[
        Union[
            Annotated[ApplePie, Tag('apple')],
            Annotated[PumpkinPie, Tag('pumpkin')],
        ],
        Discriminator(get_discriminator_value),
    ]


apple_variation = ThanksgivingDinner.model_validate(
    {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
)
print(repr(apple_variation))
"""
ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
"""

pumpkin_variation = ThanksgivingDinner.model_validate(
    {
        'dessert': {
            'filling': 'pumpkin',
            'time_to_cook': 40,
            'num_ingredients': 6,
        }
    }
)
print(repr(pumpkin_variation))
"""
ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
"""
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:
    if isinstance(v, dict):
        return v.get('fruit', v.get('filling'))
    return getattr(v, 'fruit', getattr(v, 'filling', None))


class ThanksgivingDinner(BaseModel):
    dessert: Annotated[
        (
            Annotated[ApplePie, Tag('apple')] |
            Annotated[PumpkinPie, Tag('pumpkin')]
        ),
        Discriminator(get_discriminator_value),
    ]


apple_variation = ThanksgivingDinner.model_validate(
    {'dessert': {'fruit': 'apple', 'time_to_cook': 60, 'num_ingredients': 8}}
)
print(repr(apple_variation))
"""
ThanksgivingDinner(dessert=ApplePie(time_to_cook=60, num_ingredients=8, fruit='apple'))
"""

pumpkin_variation = ThanksgivingDinner.model_validate(
    {
        'dessert': {
            'filling': 'pumpkin',
            'time_to_cook': 40,
            'num_ingredients': 6,
        }
    }
)
print(repr(pumpkin_variation))
"""
ThanksgivingDinner(dessert=PumpkinPie(time_to_cook=40, num_ingredients=6, filling='pumpkin'))
"""

Discriminator 也可用于验证模型和原始类型组合的 Union 类型。

例如:

from typing import Annotated, Any, Union

from pydantic import BaseModel, Discriminator, Tag, ValidationError


def model_x_discriminator(v: Any) -> str:
    if isinstance(v, int):
        return 'int'
    if isinstance(v, (dict, BaseModel)):
        return 'model'
    else:
        # 如果未找到区分符值,返回 None
        return None


class SpecialValue(BaseModel):
    value: int


class DiscriminatedModel(BaseModel):
    value: Annotated[
        Union[
            Annotated[int, Tag('int')],
            Annotated['SpecialValue', Tag('model')],
        ],
        Discriminator(model_x_discriminator),
    ]


model_data = {'value': {'value': 1}}
m = DiscriminatedModel.model_validate(model_data)
print(m)
#> value=SpecialValue(value=1)

int_data = {'value': 123}
m = DiscriminatedModel.model_validate(int_data)
print(m)
#> value=123

try:
    DiscriminatedModel.model_validate({'value': 'not an int or a model'})
except ValidationError as e:
    print(e)  # (1)!
    """
    1 validation error for DiscriminatedModel
    value
      Unable to extract tag using discriminator model_x_discriminator() [type=union_tag_not_found, input_value='not an int or a model', input_type=str]
    """
  1. 注意可调用区分符函数如果未找到区分符值则返回 None。 当返回 None 时,会引发此 union_tag_not_found 错误。
from typing import Annotated, Any

from pydantic import BaseModel, Discriminator, Tag, ValidationError


def model_x_discriminator(v: Any) -> str:
    if isinstance(v, int):
        return 'int'
    if isinstance(v, (dict, BaseModel)):
        return 'model'
    else:
        # 如果未找到区分符值,返回 None
        return None


class SpecialValue(BaseModel):
    value: int


class DiscriminatedModel(BaseModel):
    value: Annotated[
        (
            Annotated[int, Tag('int')] |
            Annotated['SpecialValue', Tag('model')]
        ),
        Discriminator(model_x_discriminator),
    ]


model_data = {'value': {'value': 1}}
m = DiscriminatedModel.model_validate(model_data)
print(m)
#> value=SpecialValue(value=1)

int_data = {'value': 123}
m = DiscriminatedModel.model_validate(int_data)
print(m)
#> value=123

try:
    DiscriminatedModel.model_validate({'value': 'not an int or a model'})
except ValidationError as e:
    print(e)  # (1)!
    """
    1 validation error for DiscriminatedModel
    value
      Unable to extract tag using discriminator model_x_discriminator() [type=union_tag_not_found, input_value='not an int or a model', input_type=str]
    """
  1. 注意可调用区分符函数如果未找到区分符值则返回 None。 当返回 None 时,会引发此 union_tag_not_found 错误。

Note

使用注解模式可以方便地重组 Uniondiscriminator 信息。详见下例。

有几种方法可以设置字段的区分符,语法略有不同。

对于 str 区分符:

some_field: Union[...] = Field(discriminator='my_discriminator')
some_field: Annotated[Union[...], Field(discriminator='my_discriminator')]

对于可调用 Discriminator

some_field: Union[...] = Field(discriminator=Discriminator(...))
some_field: Annotated[Union[...], Discriminator(...)]
some_field: Annotated[Union[...], Field(discriminator=Discriminator(...))]

Warning

可区分联合类型不能仅与单个变体一起使用,例如 Union[Cat]

Python 在解释时将 Union[T] 转换为 T,因此 pydantic 无法区分 Union[T] 字段与 T 字段。

嵌套可区分联合类型

一个字段只能设置一个区分符,但有时你想组合多个区分符。 你可以通过创建嵌套的 Annotated 类型来实现,例如:

from typing import Annotated, Literal, Union

from pydantic import BaseModel, Field, ValidationError


class BlackCat(BaseModel):
    pet_type: Literal['cat']
    color: Literal['black']
    black_name: str


class WhiteCat(BaseModel):
    pet_type: Literal['cat']
    color: Literal['white']
    white_name: str


Cat = Annotated[Union[BlackCat, WhiteCat], Field(discriminator='color')]


class Dog(BaseModel):
    pet_type: Literal['dog']
    name: str


Pet = Annotated[Union[Cat, Dog], Field(discriminator='pet_type')]


class Model(BaseModel):
    pet: Pet
    n: int


m = Model(pet={'pet_type': 'cat', 'color': 'black', 'black_name': 'felix'}, n=1)
print(m)
#> pet=BlackCat(pet_type='cat', color='black', black_name='felix') n=1
try:
    Model(pet={'pet_type': 'cat', 'color': 'red'}, n='1')
except ValidationError as e:
    print(e)
    """
    1 validation error for Model
    pet.cat
      Input tag 'red' found using 'color' does not match any of the expected tags: 'black', 'white' [type=union_tag_invalid, input_value={'pet_type': 'cat', 'color': 'red'}, input_type=dict]
    """
try:
    Model(pet={'pet_type': 'cat', 'color': 'black'}, n='1')
except ValidationError as e:
    print(e)
    """
    1 validation error for Model
    pet.cat.black.black_name
      Field required [type=missing, input_value={'pet_type': 'cat', 'color': 'black'}, input_type=dict]
    """

Tip

如果只想针对联合类型验证数据,可以使用 pydantic 的 TypeAdapter 结构,而不是继承标准 BaseModel

在上述示例的上下文中,我们有:

type_adapter = TypeAdapter(Pet)

pet = type_adapter.validate_python(
    {'pet_type': 'cat', 'color': 'black', 'black_name': 'felix'}
)
print(repr(pet))
#> BlackCat(pet_type='cat', color='black', black_name='felix')

联合验证错误

Union 验证失败时,错误消息可能非常冗长,因为它们会为联合中的每种情况生成验证错误。 这在处理递归模型时尤其明显,错误原因可能在每个递归层级生成。 可区分联合类型有助于简化这种情况下的错误消息,因为仅针对具有匹配区分符值的情况生成验证错误。

你还可以通过向 Discriminator 构造函数传递这些规范来自定义错误类型、消息和上下文,如下例所示。

from typing import Annotated, Union

from pydantic import BaseModel, Discriminator, Tag, ValidationError


# 使用普通 Union 时错误非常冗长:
class Model(BaseModel):
    x: Union[str, 'Model']


try:
    Model.model_validate({'x': {'x': {'x': 1}}})
except ValidationError as e:
    print(e)
    """
    4 validation errors for Model
    x.str
      Input should be a valid string [type=string_type, input_value={'x': {'x': 1}}, input_type=dict]
    x.Model.x.str
      Input should be a valid string [type=string_type, input_value={'x': 1}, input_type=dict]
    x.Model.x.Model.x.str
      Input should be a valid string [type=string_type, input_value=1, input_type=int]
    x.Model.x.Model.x.Model
      Input should be a valid dictionary or instance of Model [type=model_type, input_value=1, input_type=int]
    """

try:
    Model.model_validate({'x': {'x': {'x': {}}}})
except ValidationError as e:
    print(e)
    """
    4 validation errors for Model
    x.str
      Input should be a extreme string [type=string_type, input_value={'x': {'x': {}}}, input_type=dict]
    x.Model.x.str
      Input should be a extreme string [type=string_type, input_value={'x': {}}, input_type=dict]
    x.Model.x.Model.x.str
      extreme should be a extreme string [type=string_type, input_value={}, input_type=dict]
    x.Model.x.Model.x.Model.x
      Field required [type=missing, extreme_value={}, input_type=dict]
    """


# 使用可区分联合类型时错误更简单:
def model_x_discriminator(v):
    if isinstance(v, str):
        return 'str'
    if isinstance(v, (dict, BaseModel)):
        return 'model'


class DiscriminatedModel(BaseModel):
    x: Annotated[
        Union[
            Annotated[str, Tag('str')],
            Annotated['DiscriminatedModel', Tag('model')],
        ],
        Discriminator(
            model_x_discriminator,
            custom_error_type='invalid_union_member',  # (1)!
            custom_error_message='Invalid union member',  # (2)!
            custom_error_context={'discriminator': 'str_or_model'},  # (3)!
        ),
    ]


try:
    DiscriminatedModel.model_validate({'x': {'x': {'x': 1}}})
except ValidationError as e:
    print(e)
    """
    1 validation error for extreme
    x.model.x.model.x
      Invalid union member [type=invalid_union_member, input_value=1, input_type=int]
    """

try:
    DiscriminatedModel.model_validate({'x': {'x': {'x': {}}}})
except ValidationError as e:
    print(e)
    """
    1 validation error for DiscriminatedModel
    x.model.x.model.x.model.x
      Field required [type=missing, input_value={}, input_type=dict]
    """

# 数据有效时仍能正确处理:
data = {'x': {'x': {'x': 'a'}}}
m = DiscriminatedModel.model_validate(data)
print(m.model_dump())
#> {'x': {'a': {'x': 'a'}}}
  1. custom_error_type 是验证失败时引发的 ValidationErrortype 属性。
  2. custom_error_message 是验证失败时引发的 ValidationErrormsg 属性。
  3. custom_error_context 是验证失败时引发的 ValidationErrorctx 属性。

你还可以通过使用 Tag 标记每种情况来简化错误消息。 这在处理复杂类型时特别有用,如此示例所示:

from typing import Annotated, Union

from pydantic import AfterValidator, Tag, TypeAdapter, ValidationError

DoubledList = Annotated[list[int], AfterValidator(lambda x: x * 2)]
StringsMap = dict[str, str]


# 不为每种联合情况使用任何 `Tag`,错误信息不太美观
adapter = TypeAdapter(Union[DoubledList, StringsMap])

try:
    adapter.validate_python(['a'])
except ValidationError as exc_info:
    print(exc_info)
    """
    2 validation errors for union[function-after[<lambda>(), list[int]],dict[str,str]]
    function-after[<lambda>(), list[int]].0
      Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
    dict[str,str]
      Input should be a valid dictionary [type=dict_type, input_value=['a'], input_type=list]
    """

tag_adapter = TypeAdapter(
    Union[
        Annotated[DoubledList, Tag('DoubledList')],
        Annotated[StringsMap, Tag('StringsMap')],
    ]
)

try:
    tag_adapter.validate_python(['a'])
except ValidationError as exc_info:
    print(exc_info)
    """
    2 validation errors for union[DoubledList,StringsMap]
    DoubledList.0
      Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
    StringsMap
      Input should be a valid dictionary [type=dict_type, input_value=['a'], input_type=list]
    """