标准库类型
Pydantic 支持 Python 标准库中的许多常见类型。如果需要更严格的处理,请参阅严格类型,包括如果需要限制允许的值(例如,要求为正 int )。
布尔值¶
如果值不是以下内容之一,则标准 bool 字段将引发 ValidationError :
- 有效的布尔值(即
True或False), - 整数
0或1 - a
str当其转换为小写时是'0', 'off', 'f', 'false', 'n', 'no', '1', 'on', 't', 'true', 'y', 'yes'之一 - 根据前一个规则,当解码为
str时,abytes是有效的
注意
如果您想要更严格的布尔逻辑(例如,只允许 True 和 False 的字段),可以使用 StrictBool 。
以下是一个演示其中一些行为的脚本:
from pydantic import BaseModel, ValidationError
class BooleanModel(BaseModel):
bool_value: bool
print(BooleanModel(bool_value=False))
#> bool_value=False
print(BooleanModel(bool_value='False'))
#> bool_value=False
print(BooleanModel(bool_value=1))
#> bool_value=True
try:
BooleanModel(bool_value=[])
except ValidationError as e:
print(str(e))
"""
1 validation error for BooleanModel
bool_value
Input should be a valid boolean [type=bool_type, input_value=[], input_type=list]
"""
日期时间类型¶
Pydantic 支持以下日期时间类型:
datetime.datetime¶
-
datetime个字段将接受以下类型的值:datetime;现有datetime对象int或float;被视为 Unix 时间,即自 1970 年 1 月 1 日以来的秒数(如果大于等于-2e10且小于等于2e10)或毫秒数(如果小于-2e10或大于2e10)str;以下格式被接受:YYYY-MM-DD[T]HH:MM[:SS[.ffffff]][Z or [±]HH[:]MM]- 在宽松模式下接受
YYYY-MM-DD,但在严格模式下不接受 int或float作为字符串(假设为 Unix 时间)
- 在宽松模式下接受 [
datetime.date][ `datetime.date` ] 实例,但在严格模式下不接受
from datetime import datetime
from pydantic import BaseModel
class Event(BaseModel):
dt: datetime = None
event = Event(dt='2032-04-23T10:20:30.400+02:30')
print(event.model_dump())
"""
{'dt': datetime.datetime(2032, 4, 23, 10, 20, 30, 400000, tzinfo=TzInfo(+02:30))}
"""
datetime.date¶
-
date个字段将接受以下类型的值: -
date;现有date对象 int或float;处理方式与上文对datetime的描述相同str;接受以下格式:YYYY-MM-DDint或float作为字符串(假设为 Unix 时间)
from datetime import date
from pydantic import BaseModel
class Birthday(BaseModel):
d: date = None
my_birthday = Birthday(d=1679616000.0)
print(my_birthday.model_dump())
#> {'d': datetime.date(2023, 3, 24)}
datetime.time¶
-
time个字段将接受以下类型的值:time;现有time对象str;以下格式被接受:HH:MM[:SS[.ffffff]][Z or [±]HH[:]MM]
from datetime import time
from pydantic import BaseModel
class Meeting(BaseModel):
t: time = None
m = Meeting(t=time(4, 8, 16))
print(m.model_dump())
#> {'t': datetime.time(4, 8, 16)}
datetime.timedelta¶
-
timedelta个字段将接受以下类型的值:timedelta;现有timedelta对象int或float;假定为秒str;以下格式被接受:[-][DD]D[,][HH:MM:]SS[.ffffff]- 例如:
'1d,01:02:03.000004'或'1D01:02:03.000004'或'01:02:03'
- 例如:
[±]P[DD]DT[HH]H[MM]M[SS]S(时间间隔的 ISO 8601 格式)
from datetime import timedelta
from pydantic import BaseModel
class Model(BaseModel):
td: timedelta = None
m = Model(td='P3DT12H30M5S')
print(m.model_dump())
#> {'td': datetime.timedelta(days=3, seconds=45005)}
数字类型¶
Pydantic 支持 Python 标准库中的以下数值类型:
int¶
- Pydantic 使用
int(v)将类型强制转换为int;有关数据转换期间信息丢失的详细信息,请参阅数据转换。
float¶
- Pydantic 使用
float(v)将值强制转换为浮点数。
enum.IntEnum¶
- 验证:Pydantic 检查该值是否为有效的
IntEnum实例。 - 对
enum.IntEnum的子类进行验证:检查该值是否是整数枚举的有效成员;有关详细信息,请参阅枚举和选择。
decimal.Decimal¶
- 验证:Pydantic 尝试将该值转换为字符串,然后将该字符串传递给
Decimal(v)。 - 序列化:Pydantic 将
Decimal类型序列化为字符串。如果需要,可以使用自定义序列化程序来覆盖此行为。例如:
from decimal import Decimal
from typing_extensions import Annotated
from pydantic import BaseModel, PlainSerializer
class Model(BaseModel):
x: Decimal
y: Annotated[
Decimal,
PlainSerializer(
lambda x: float(x), return_type=float, when_used='json'
),
]
my_model = Model(x=Decimal('1.1'), y=Decimal('2.1'))
print(my_model.model_dump()) # (1)!
#> {'x': Decimal('1.1'), 'y': Decimal('2.1')}
print(my_model.model_dump(mode='json')) # (2)!
#> {'x': '1.1', 'y': 2.1}
print(my_model.model_dump_json()) # (3)!
#> {"x":"1.1","y":2.1}
-
使用
model_dump,x和y仍然是Decimal类型的实例。 -
使用
model_dump结合mode='json',由于应用了自定义序列化程序,x被序列化为string,y被序列化为float。 -
使用
model_dump_json,由于应用了自定义序列化程序,x被序列化为string,y被序列化为float。
[枚举类型]¶
Pydantic 使用 Python 的标准 enum 类来定义选择。
enum.Enum 检查该值是否为有效的 Enum 实例。 enum.Enum 的子类检查该值是否为枚举的有效成员。
from enum import Enum, IntEnum
from pydantic import BaseModel, ValidationError
class FruitEnum(str, Enum):
pear = 'pear'
banana = 'banana'
class ToolEnum(IntEnum):
spanner = 1
wrench = 2
class CookingModel(BaseModel):
fruit: FruitEnum = FruitEnum.pear
tool: ToolEnum = ToolEnum.spanner
print(CookingModel())
#> fruit=<FruitEnum.pear: 'pear'> tool=<ToolEnum.spanner: 1>
print(CookingModel(tool=2, fruit='banana'))
#> fruit=<FruitEnum.banana: 'banana'> tool=<ToolEnum.wrench: 2>
try:
CookingModel(fruit='other')
except ValidationError as e:
print(e)
"""
1 validation error for CookingModel
fruit
Input should be 'pear' or 'banana' [type=enum, input_value='other', input_type=str]
"""
列表和元组¶
list¶
允许 list 、 tuple 、 set 、 frozenset 、 deque 或生成器转换为 list 。当提供泛型参数时,将对列表中的所有项应用适当的验证。
typing.List¶
处理方式与 list 相同。
from typing import List, Optional
from pydantic import BaseModel
class Model(BaseModel):
simple_list: Optional[list] = None
list_of_ints: Optional[List[int]] = None
print(Model(simple_list=['1', '2', '3']).simple_list)
#> ['1', '2', '3']
print(Model(list_of_ints=['1', '2', '3']).list_of_ints)
#> [1, 2, 3]
tuple¶
允许 list 、 tuple 、 set 、 frozenset 、 deque 或生成器转换为 tuple 。当提供泛型参数时,将对元组的相应项应用适当的验证
typing.Tuple¶
与上面的 tuple 处理方式相同。
from typing import Optional, Tuple
from pydantic import BaseModel
class Model(BaseModel):
simple_tuple: Optional[tuple] = None
tuple_of_different_types: Optional[Tuple[int, float, bool]] = None
print(Model(simple_tuple=[1, 2, 3, 4]).simple_tuple)
#> (1, 2, 3, 4)
print(Model(tuple_of_different_types=[3, 2, 1]).tuple_of_different_types)
#> (3, 2.0, True)
typing.NamedTuple¶
[ typing.NamedTuple ] 的子类类似于 tuple ,但会创建给定 namedtuple 类的实例。
[ collections.namedtuple ][ `collections.namedtuple` ] 的子类类似于 [ typing.NamedTuple ][ `typing.NamedTuple` ] 的子类,但由于未指定字段类型,因此所有字段都被视为具有类型 Any 。
from typing import NamedTuple
from pydantic import BaseModel, ValidationError
class Point(NamedTuple):
x: int
y: int
class Model(BaseModel):
p: Point
try:
Model(p=('1.3', '2'))
except ValidationError as e:
print(e)
"""
1 validation error for Model
p.0
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='1.3', input_type=str]
"""
双端队列¶
[双向队列]¶
允许 list 、 tuple 、 set 、 frozenset 、 deque 或生成器和转换为 deque 。当提供泛型参数时,将对 deque 的相应项应用适当的验证。
typing.Deque¶
与上面的 deque 处理方式相同。
from typing import Deque, Optional
from pydantic import BaseModel
class Model(BaseModel):
deque: Optional[Deque[int]] = None
print(Model(deque=[1, 2, 3]).deque)
#> deque([1, 2, 3])
集合¶
set¶
允许 list 、 tuple 、 set 、 frozenset 、 deque 或生成器转换为 set 。当提供泛型参数时,将对集合中的所有项应用适当的验证。
typing.Set¶
与上面的 set 处理方式相同。
from typing import Optional, Set
from pydantic import BaseModel
class Model(BaseModel):
simple_set: Optional[set] = None
set_of_ints: Optional[Set[int]] = None
print(Model(simple_set={'1', '2', '3'}).simple_set)
#> {'1', '2', '3'}
print(Model(simple_set=['1', '2', '3']).simple_set)
#> {'1', '2', '3'}
print(Model(set_of_ints=['1', '2', '3']).set_of_ints)
#> {1, 2, 3}
frozenset¶
允许 list 、 tuple 、 set 、 frozenset 、 deque 或生成器转换为 frozenset 。当提供泛型参数时,将对冻结集的所有项应用适当的验证。
typing.FrozenSet¶
处理方式同上一个 frozenset 。
from typing import FrozenSet, Optional
from pydantic import BaseModel
class Model(BaseModel):
simple_frozenset: Optional[frozenset] = None
frozenset_of_ints: Optional[FrozenSet[int]] = None
m1 = Model(simple_frozenset=['1', '2', '3'])
print(type(m1.simple_frozenset))
#> <class 'frozenset'>
print(sorted(m1.simple_frozenset))
#> ['1', '2', '3']
m2 = Model(frozenset_of_ints=['1', '2', '3'])
print(type(m2.frozenset_of_ints))
#> <class 'frozenset'>
print(sorted(m2.frozenset_of_ints))
#> [1, 2, 3]
其他可迭代对象¶
typing.Sequence¶
这是为了在提供的值应满足 Sequence ABC 的要求时使用的,并且希望对容器中的值进行急切验证。请注意,当必须对容器的值进行验证时,容器的类型可能不会保留,因为验证可能最终会替换值。我们保证验证后的有效值将是有效的 [ typing.Sequence ][ `typing.Sequence` ],但它可能与提供的值具有不同的类型(通常,它将成为 list )。
typing.Iterable¶
这用于提供的值可能是一个不可消耗的可迭代对象的情况。有关解析和验证的更多详细信息,请参见下面的无限生成器。与 [ typing.Sequence ][ `typing.Sequence` ] 类似,我们保证经过验证的结果将是有效的 [ typing.Iterable ][ `typing.Iterable` ],但它的类型可能与提供的类型不同。特别是,即使提供了非生成器类型,例如 list ,[ typing.Iterable ][ `typing.Iterable` ] 类型字段的后验证值也将是生成器。
这里有一个简单的示例,使用了[ typing.Sequence ]:
from typing import Sequence
from pydantic import BaseModel
class Model(BaseModel):
sequence_of_ints: Sequence[int] = None
print(Model(sequence_of_ints=[1, 2, 3, 4]).sequence_of_ints)
#> [1, 2, 3, 4]
print(Model(sequence_of_ints=(1, 2, 3, 4)).sequence_of_ints)
#> (1, 2, 3, 4)
无限发电机¶
如果您有要验证的生成器,可以按照上述说明使用 Sequence 。在这种情况下,生成器将被消耗并存储在模型中作为列表,其值将根据 Sequence (例如 Sequence[int] 中的 int )的类型参数进行验证。
然而,如果你有一个不想被急切消耗的生成器(例如无限生成器或远程数据加载器),你可以使用类型为 Iterable 的字段:
from typing import Iterable
from pydantic import BaseModel
class Model(BaseModel):
infinite: Iterable[int]
def infinite_ints():
i = 0
while True:
yield i
i += 1
m = Model(infinite=infinite_ints())
print(m)
"""
infinite=ValidatorIterator(index=0, schema=Some(Int(IntValidator { strict: false })))
"""
for i in m.infinite:
print(i)
#> 0
#> 1
#> 2
#> 3
#> 4
#> 5
#> 6
#> 7
#> 8
#> 9
#> 10
if i == 10:
break
警告
在初始验证期间, Iterable 字段仅执行对提供的参数是否可迭代的简单检查。为了防止它被消耗,不会急切地对生成的值进行任何验证。
虽然生成的值没有被及时验证,但它们在生成时仍然会被验证,并且在适当的时候会在生成时引发 ValidationError :
from typing import Iterable
from pydantic import BaseModel, ValidationError
class Model(BaseModel):
int_iterator: Iterable[int]
def my_iterator():
yield 13
yield '27'
yield 'a'
m = Model(int_iterator=my_iterator())
print(next(m.int_iterator))
#> 13
print(next(m.int_iterator))
#> 27
try:
next(m.int_iterator)
except ValidationError as e:
print(e)
"""
1 validation error for ValidatorIterator
2
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='a', input_type=str]
"""
映射类型¶
dict¶
dict(v) 用于尝试转换字典。请参阅下面的 [ typing.Dict ][ `typing.Dict` ] 了解子类型约束。
from pydantic import BaseModel, ValidationError
class Model(BaseModel):
x: dict
m = Model(x={'foo': 1})
print(m.model_dump())
#> {'x': {'foo': 1}}
try:
Model(x='test')
except ValidationError as e:
print(e)
"""
1 validation error for Model
x
Input should be a valid dictionary [type=dict_type, input_value='test', input_type=str]
"""
typing.Dict¶
from typing import Dict
from pydantic import BaseModel, ValidationError
class Model(BaseModel):
x: Dict[str, int]
m = Model(x={'foo': 1})
print(m.model_dump())
#> {'x': {'foo': 1}}
try:
Model(x={'foo': '1'})
except ValidationError as e:
print(e)
"""
1 validation error for Model
x
Input should be a valid dictionary [type=dict_type, input_value='test', input_type=str]
"""
字典类型¶
注意
这是 Python 标准库自 3.8 以来的新功能。由于 3.12 之前的 typing.TypedDict 的限制,对于 Python <3.12,需要 typing-extensions 包。你需要从 typing_extensions 导入 TypedDict ,而不是 typing ,否则会在构建时出错。
TypedDict 声明了一种字典类型,该类型期望其所有实例都具有一组特定的键,其中每个键都与具有一致类型的值相关联。
它与 dict 相同,但 Pydantic 将验证字典,因为键已被注释。
from typing_extensions import TypedDict
from pydantic import TypeAdapter, ValidationError
class User(TypedDict):
name: str
id: int
ta = TypeAdapter(User)
print(ta.validate_python({'name': 'foo', 'id': 1}))
#> {'name': 'foo', 'id': 1}
try:
ta.validate_python({'name': 'foo'})
except ValidationError as e:
print(e)
"""
1 validation error for typed-dict
id
Field required [type=missing, input_value={'name': 'foo'}, input_type=dict]
"""
你可以定义 pydantic_config 来更改从 [TypedDict][typing.TypedDict] 继承的模型。有关更多详细信息,请参阅 ConfigDict API 参考。
from typing import Optional
from typing_extensions import TypedDict
from pydantic import ConfigDict, TypeAdapter, ValidationError
# `total=False` means keys are non-required
class UserIdentity(TypedDict, total=False):
name: Optional[str]
surname: str
class User(TypedDict):
__pydantic_config__ = ConfigDict(extra='forbid')
identity: UserIdentity
age: int
ta = TypeAdapter(User)
print(
ta.validate_python(
{'identity': {'name': 'Smith', 'surname': 'John'}, 'age': 37}
)
)
#> {'identity': {'name': 'Smith', 'surname': 'John'}, 'age': 37}
print(
ta.validate_python(
{'identity': {'name': None, 'surname': 'John'}, 'age': 37}
)
)
#> {'identity': {'name': None, 'surname': 'John'}, 'age': 37}
print(ta.validate_python({'identity': {}, 'age': 37}))
#> {'identity': {}, 'age': 37}
try:
ta.validate_python(
{'identity': {'name': ['Smith'], 'surname': 'John'}, 'age': 24}
)
except ValidationError as e:
print(e)
"""
1 validation error for typed-dict
identity.name
Input should be a valid string [type=string_type, input_value=['Smith'], input_type=list]
"""
try:
ta.validate_python(
{
'identity': {'name': 'Smith', 'surname': 'John'},
'age': '37',
'email': 'john.smith@me.com',
}
)
except ValidationError as e:
print(e)
"""
1 validation error for typed-dict
email
Extra inputs are not permitted [type=extra_forbidden, input_value='john.smith@me.com', input_type=str]
"""
可调用的¶
请查看下面有关解析和验证的更多详细信息
字段也可以是 Callable 类型:
from typing import Callable
from pydantic import BaseModel
class Foo(BaseModel):
callback: Callable[[int], int]
m = Foo(callback=lambda x: x)
print(m)
#> callback=<function <lambda> at 0x0123456789ab>
警告
可调用字段仅执行对参数是否可调用的简单检查;不执行对参数、其类型或返回类型的任何验证。
IP 地址类型¶
-
[
ipaddress.IPv4Address][ `ipaddress.IPv4Address` ]: 使用自身类型进行验证,将值传递给IPv4Address(v)。 -
[
ipaddress.IPv4Interface][ `ipaddress.IPv4Interface` ]: 使用自身类型进行验证,将值传递给IPv4Address(v)。 -
[
ipaddress.IPv4Network][ `ipaddress.IPv4Network` ]: 使用自身类型进行验证,将值传递给IPv4Network(v)。 -
[
ipaddress.IPv6Address][ `ipaddress.IPv6Address` ]: 使用自身类型进行验证,将值传递给IPv6Address(v)。 -
[
ipaddress.IPv6Interface][ `ipaddress.IPv6Interface` ]: 使用自身类型进行验证,将值传递给IPv6Interface(v)。 -
[
ipaddress.IPv6Network][ `ipaddress.IPv6Network` ]: 使用自身类型进行验证,将值传递给IPv6Network(v)。
请参阅网络类型以了解其他自定义 IP 地址类型。
UUID¶
对于 UUID,Pydantic 尝试通过将值传递给 UUID(v) 来使用自身类型进行验证。对于 bytes 和 bytearray ,有一个回退到 UUID(bytes=v) 。
如果您想限制 UUID 版本,可以检查以下类型:
Union¶
Pydantic 对联合验证有广泛的支持,同时支持 [ typing.Union ][ `typing.Union` ] 和 Python 3.10 的管道语法( A | B )。更多信息请参考概念文档的 Unions 部分。
Type 和 TypeVar ¶
type¶
Pydantic 支持使用 type[T] 来指定一个字段只能接受 T 的子类(而不是实例)。
typing.Type¶
与上面的 type 处理方式相同。
from typing import Type
from pydantic import BaseModel, ValidationError
class Foo:
pass
class Bar(Foo):
pass
class Other:
pass
class SimpleModel(BaseModel):
just_subclasses: Type[Foo]
SimpleModel(just_subclasses=Foo)
SimpleModel(just_subclasses=Bar)
try:
SimpleModel(just_subclasses=Other)
except ValidationError as e:
print(e)
"""
1 validation error for SimpleModel
just_subclasses
Input should be a subclass of Foo [type=is_subclass_of, input_value=<class '__main__.Other'>, input_type=type]
"""
你也可以使用 Type 来指定允许任何类。
from typing import Type
from pydantic import BaseModel, ValidationError
class Foo:
pass
class LenientSimpleModel(BaseModel):
any_class_goes: Type
LenientSimpleModel(any_class_goes=int)
LenientSimpleModel(any_class_goes=Foo)
try:
LenientSimpleModel(any_class_goes=Foo())
except ValidationError as e:
print(e)
"""
1 validation error for LenientSimpleModel
any_class_goes
Input should be a type [type=is_type, input_value=<__main__.Foo object at 0x0123456789ab>, input_type=Foo]
"""
typing.TypeVar¶
TypeVar 既可以不受限制地支持,也可以受限制地支持,或者带有边界。
from typing import TypeVar
from pydantic import BaseModel
Foobar = TypeVar('Foobar')
BoundFloat = TypeVar('BoundFloat', bound=float)
IntStr = TypeVar('IntStr', int, str)
class Model(BaseModel):
a: Foobar # equivalent of ": Any"
b: BoundFloat # equivalent of ": float"
c: IntStr # equivalent of ": Union[int, str]"
print(Model(a=[1], b=4.2, c='x'))
#> a=[1] b=4.2 c='x'
# a may be None
print(Model(a=None, b=1, c=1))
#> a=None b=1.0 c=1
无类型¶
[ None ][ `None` ], type(None) ,或 Literal[None] 根据输入规范都是等效的。只允许 None 值。
字符串¶
str :字符串将被原样接受。 bytes 和 bytearray 将使用 v.decode() 进行转换。枚举 s inheriting from 字符串 are converted using 的值`。其他所有类型都会导致错误。
警告
“字符串不是序列”
While instances of str are technically valid instances of the Sequence[str] protocol from a type-checker's point of
view, this is frequently not intended as is a common source of bugs.
As a result, Pydantic raises a ValidationError if you attempt to pass a str or bytes instance into a field of type
Sequence[str] or Sequence[bytes]:
from typing import Optional, Sequence
from pydantic import BaseModel, ValidationError
class Model(BaseModel):
sequence_of_strs: Optional[Sequence[str]] = None
sequence_of_bytes: Optional[Sequence[bytes]] = None
print(Model(sequence_of_strs=['a', 'bc']).sequence_of_strs)
#> ['a', 'bc']
print(Model(sequence_of_strs=('a', 'bc')).sequence_of_strs)
#> ('a', 'bc')
print(Model(sequence_of_bytes=[b'a', b'bc']).sequence_of_bytes)
#> [b'a', b'bc']
print(Model(sequence_of_bytes=(b'a', b'bc')).sequence_of_bytes)
#> (b'a', b'bc')
try:
Model(sequence_of_strs='abc')
except ValidationError as e:
print(e)
"""
1 validation error for Model
sequence_of_strs
'str' instances are not allowed as a Sequence value [type=sequence_str, input_value='abc', input_type=str]
"""
try:
Model(sequence_of_bytes=b'abc')
except ValidationError as e:
print(e)
"""
1 validation error for Model
sequence_of_bytes
'bytes' instances are not allowed as a Sequence value [type=sequence_str, input_value=b'abc', input_type=bytes]
"""
字节跳动¶
[ ][ bytes ] 被接受为原样。[ bytearray ] 使用 bytes(v) 进行转换。[ str ] 使用 v.encode() 进行转换。[ int ]、[ float ] 和[ Decimal ] 使用 str(v).encode() 进行强制转换。有关更多详细信息,请参阅 ByteSize。
typing.Literal¶
Pydantic 支持使用 [ typing.Literal ][ `typing.Literal` ] 作为一种轻量级的方式来指定一个字段只能接受特定的文字值:
from typing import Literal
from pydantic import BaseModel, ValidationError
class Pie(BaseModel):
flavor: Literal['apple', 'pumpkin']
Pie(flavor='apple')
Pie(flavor='pumpkin')
try:
Pie(flavor='cherry')
except ValidationError as e:
print(str(e))
"""
1 validation error for Pie
flavor
Input should be 'apple' or 'pumpkin' [type=literal_error, input_value='cherry', input_type=str]
"""
这种字段类型的一个好处是,它可以用于检查与一个或多个特定值的相等性,而无需声明自定义验证器:
from typing import ClassVar, List, Literal, Union
from pydantic import BaseModel, ValidationError
class Cake(BaseModel):
kind: Literal['cake']
required_utensils: ClassVar[List[str]] = ['fork', 'knife']
class IceCream(BaseModel):
kind: Literal['icecream']
required_utensils: ClassVar[List[str]] = ['spoon']
class Meal(BaseModel):
dessert: Union[Cake, IceCream]
print(type(Meal(dessert={'kind': 'cake'}).dessert).__name__)
#> Cake
print(type(Meal(dessert={'kind': 'icecream'}).dessert).__name__)
#> IceCream
try:
Meal(dessert={'kind': 'pie'})
except ValidationError as e:
print(str(e))
"""
2 validation errors for Meal
dessert.Cake.kind
Input should be 'cake' [type=literal_error, input_value='pie', input_type=str]
dessert.IceCream.kind
Input should be 'icecream' [type=literal_error, input_value='pie', input_type=str]
"""
在注释的 Union 中有适当的排序,您可以使用它来解析特定性逐渐降低的类型:
from typing import Literal, Optional, Union
from pydantic import BaseModel
class Dessert(BaseModel):
kind: str
class Pie(Dessert):
kind: Literal['pie']
flavor: Optional[str]
class ApplePie(Pie):
flavor: Literal['apple']
class PumpkinPie(Pie):
flavor: Literal['pumpkin']
class Meal(BaseModel):
dessert: Union[ApplePie, PumpkinPie, Pie, Dessert]
print(type(Meal(dessert={'kind': 'pie', 'flavor': 'apple'}).dessert).__name__)
#> ApplePie
print(type(Meal(dessert={'kind': 'pie', 'flavor': 'pumpkin'}).dessert).__name__)
#> PumpkinPie
print(type(Meal(dessert={'kind': 'pie'}).dessert).__name__)
#> Dessert
print(type(Meal(dessert={'kind': 'cake'}).dessert).__name__)
#> Dessert
typing.Any¶
允许任何值,包括 None 。
typing.Annotated¶
允许根据 PEP-593 用任意元数据包装另一种类型。 Annotated 提示可以包含对 Field 函数的单次调用,但除此之外,其他额外的元数据将被忽略,并且使用根类型。
typing.Pattern¶
将输入值传递给 re.compile(v) 以创建正则表达式模式。
pathlib.Path¶
仅通过将值传递给 Path(v) 来使用自身类型进行验证。
本文总阅读量次