TypeAdapter
基类:Generic[T]
使用文档
类型适配器提供了一种灵活的方式,可以基于 Python 类型执行验证和序列化。
TypeAdapter
实例公开了 BaseModel
实例方法的一些功能,用于不具备这些方法的类型(例如数据类、原始类型等)。
注意: TypeAdapter
实例不是类型,不能用作字段的类型注解。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
type
|
Any
|
与 |
必需 |
config
|
ConfigDict | None
|
注意 如果正在使用的类型有自己的不可覆盖的配置(例如: |
None
|
_parent_depth
|
int
|
搜索 父框架 的深度。 此框架在模式构建期间解析前向注解时使用,方法是查找此框架的全局变量和局部变量。 默认为 2,这将导致 注意 此参数以带下划线的方式命名,以暗示其私有性质并劝阻使用。 它可能会在次要版本中被弃用,因此我们仅建议在您对行为/支持的潜在更改感到满意的情况下使用它。 它的默认值为 2,因为在内部, |
2
|
module
|
str | None
|
如果提供,则传递给插件的模块。 |
None
|
属性
名称 | 类型 | 描述 |
---|---|---|
core_schema |
CoreSchema
|
类型的核心模式。 |
validator |
SchemaValidator | PluggableSchemaValidator
|
类型的模式验证器。 |
serializer |
SchemaSerializer
|
类型的模式序列化器。 |
pydantic_complete |
bool
|
类型核心模式是否成功构建。 |
与 mypy
的兼容性
根据使用的类型,实例化 TypeAdapter
时 mypy
可能会引发错误。 作为一种解决方法,您可以显式注解您的变量
from typing import Union
from pydantic import TypeAdapter
ta: TypeAdapter[Union[str, int]] = TypeAdapter(Union[str, int]) # type: ignore[arg-type]
命名空间管理细微之处和实现细节
在此,我们收集了一些关于命名空间管理的注释,以及与 BaseModel
的细微差别
BaseModel
使用其自身的 __module__
来找出其定义位置,然后在这些全局变量中查找符号以解析前向引用。 另一方面,TypeAdapter
可以使用任意对象进行初始化,这些对象可能不是类型,因此不具有可用的 __module__
。 因此,我们转而查看父堆栈框架中的全局变量。
期望传递给此函数的 ns_resolver
将具有我们正在适配的类型的正确命名空间。 有关构建此命名空间的各种方法,请参阅 TypeAdapter.__init__
和 TypeAdapter.rebuild
的源代码。
这适用于在此函数在模块中调用的情况,该模块在其作用域中具有前向引用的目标,但并非始终适用于更复杂的情况。
例如,以下列代码为例
IntList = list[int]
OuterDict = dict[str, 'IntList']
from a import OuterDict
from pydantic import TypeAdapter
IntList = int # replaces the symbol the forward reference is looking for
v = TypeAdapter(OuterDict)
v({'x': 1}) # should fail but doesn't
如果 OuterDict
是 BaseModel
,这将起作用,因为它会在 a.py
命名空间内解析前向引用。 但是 TypeAdapter(OuterDict)
无法确定 OuterDict
来自哪个模块。
换句话说,并非所有前向引用都存在于我们正在调用的模块中的假设在技术上并不总是正确的。 尽管大多数时候都是这样,并且对于递归模型等情况效果很好,但 BaseModel
的行为也不是完美的,并且可能以类似的方式中断,因此两者之间没有对错之分。
但至少此行为与 BaseModel
的行为略有不同。
pydantic/type_adapter.py
中的源代码
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
rebuild ¶
rebuild(
*,
force: bool = False,
raise_errors: bool = True,
_parent_namespace_depth: int = 2,
_types_namespace: MappingNamespace | None = None
) -> bool | None
尝试为适配器类型重建 pydantic-core 模式。
当注解之一是 ForwardRef 且在初始尝试构建模式期间无法解析,并且自动重建失败时,这可能是必要的。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
force
|
bool
|
是否强制重建类型适配器的模式,默认为 |
False
|
raise_errors
|
bool
|
是否引发错误,默认为 |
True
|
_parent_namespace_depth
|
int
|
搜索 父框架 的深度。 此框架在模式重建期间解析前向注解时使用,方法是查找此框架的局部变量。 默认为 2,这将导致调用该方法的框架。 |
2
|
_types_namespace
|
MappingNamespace | None
|
要使用的显式类型命名空间,而不是使用父框架中的本地命名空间。 默认为 |
None
|
返回
类型 | 描述 |
---|---|
bool | None
|
如果模式已“完整”且不需要重建,则返回 |
bool | None
|
如果需要重建,则重建成功返回 |
pydantic/type_adapter.py
中的源代码
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
|
validate_python ¶
validate_python(
object: Any,
/,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
experimental_allow_partial: (
bool | Literal["off", "on", "trailing-strings"]
) = False,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> T
根据模型验证 Python 对象。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
object
|
Any
|
要根据模型验证的 Python 对象。 |
必需 |
strict
|
bool | None
|
是否严格检查类型。 |
None
|
from_attributes
|
bool | None
|
是否从对象属性中提取数据。 |
None
|
context
|
dict[str, Any] | None
|
要传递给验证器的附加上下文。 |
None
|
experimental_allow_partial
|
bool | Literal['off', 'on', 'trailing-strings']
|
实验性 是否启用 部分验证,例如处理流。 * False / 'off':默认行为,不进行部分验证。 * True / 'on':启用部分验证。 * 'trailing-strings':启用部分验证并允许输入中包含尾随字符串。 |
False
|
by_alias
|
bool | None
|
在针对提供的输入数据进行验证时,是否使用字段的别名。 |
None
|
by_name
|
bool | None
|
在针对提供的输入数据进行验证时,是否使用字段的名称。 |
None
|
注意
将 TypeAdapter
与 Pydantic dataclass
一起使用时,不支持使用 from_attributes
参数。
返回
类型 | 描述 |
---|---|
T
|
验证后的对象。 |
pydantic/type_adapter.py
中的源代码
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 |
|
validate_json ¶
validate_json(
data: str | bytes | bytearray,
/,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
experimental_allow_partial: (
bool | Literal["off", "on", "trailing-strings"]
) = False,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> T
使用文档
根据模型验证 JSON 字符串或字节。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
data
|
str | bytes | bytearray
|
要根据模型验证的 JSON 数据。 |
必需 |
strict
|
bool | None
|
是否严格检查类型。 |
None
|
context
|
dict[str, Any] | None
|
在验证期间使用的附加上下文。 |
None
|
experimental_allow_partial
|
bool | Literal['off', 'on', 'trailing-strings']
|
实验性 是否启用 部分验证,例如处理流。 * False / 'off':默认行为,不进行部分验证。 * True / 'on':启用部分验证。 * 'trailing-strings':启用部分验证并允许输入中包含尾随字符串。 |
False
|
by_alias
|
bool | None
|
在针对提供的输入数据进行验证时,是否使用字段的别名。 |
None
|
by_name
|
bool | None
|
在针对提供的输入数据进行验证时,是否使用字段的名称。 |
None
|
返回
类型 | 描述 |
---|---|
T
|
验证后的对象。 |
pydantic/type_adapter.py
中的源代码
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 |
|
validate_strings ¶
validate_strings(
obj: Any,
/,
*,
strict: bool | None = None,
context: dict[str, Any] | None = None,
experimental_allow_partial: (
bool | Literal["off", "on", "trailing-strings"]
) = False,
by_alias: bool | None = None,
by_name: bool | None = None,
) -> T
验证对象是否包含字符串数据以符合模型。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
obj
|
Any
|
包含要验证的字符串数据的对象。 |
必需 |
strict
|
bool | None
|
是否严格检查类型。 |
None
|
context
|
dict[str, Any] | None
|
在验证期间使用的附加上下文。 |
None
|
experimental_allow_partial
|
bool | Literal['off', 'on', 'trailing-strings']
|
实验性 是否启用 部分验证,例如处理流。 * False / 'off':默认行为,不进行部分验证。 * True / 'on':启用部分验证。 * 'trailing-strings':启用部分验证并允许输入中包含尾随字符串。 |
False
|
by_alias
|
bool | None
|
在针对提供的输入数据进行验证时,是否使用字段的别名。 |
None
|
by_name
|
bool | None
|
在针对提供的输入数据进行验证时,是否使用字段的名称。 |
None
|
返回
类型 | 描述 |
---|---|
T
|
验证后的对象。 |
pydantic/type_adapter.py
中的源代码
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 |
|
get_default_value ¶
get_default_value(
*,
strict: bool | None = None,
context: dict[str, Any] | None = None
) -> Some[T] | None
获取包装类型的默认值。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
strict
|
bool | None
|
是否严格检查类型。 |
None
|
context
|
dict[str, Any] | None
|
要传递给验证器的附加上下文。 |
None
|
返回
类型 | 描述 |
---|---|
Some[T] | None
|
默认值,如果存在则包装在 |
pydantic/type_adapter.py
中的源代码
520 521 522 523 524 525 526 527 528 529 530 |
|
dump_python ¶
dump_python(
instance: T,
/,
*,
mode: Literal["json", "python"] = "python",
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: (
bool | Literal["none", "warn", "error"]
) = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: dict[str, Any] | None = None,
) -> Any
将适配类型的实例转储为 Python 对象。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
instance
|
T
|
要序列化的 Python 对象。 |
必需 |
mode
|
Literal['json', 'python']
|
输出格式。 |
'python'
|
include
|
IncEx | None
|
要包含在输出中的字段。 |
None
|
exclude
|
IncEx | None
|
要从输出中排除的字段。 |
None
|
by_alias
|
bool | None
|
是否对字段名称使用别名。 |
None
|
exclude_unset
|
bool
|
是否排除未设置的字段。 |
False
|
exclude_defaults
|
bool
|
是否排除具有默认值的字段。 |
False
|
exclude_none
|
bool
|
是否排除值为 None 的字段。 |
False
|
round_trip
|
bool
|
是否以与反序列化兼容的方式输出序列化数据。 |
False
|
warnings
|
bool | Literal['none', 'warn', 'error']
|
如何处理序列化错误。 False/"none" 忽略它们,True/"warn" 记录错误,"error" 引发 |
True
|
fallback
|
Callable[[Any], Any] | None
|
遇到未知值时要调用的函数。 如果未提供,则会引发 |
None
|
serialize_as_any
|
bool
|
是否使用鸭子类型序列化行为序列化字段。 |
False
|
context
|
dict[str, Any] | None
|
要传递给序列化器的附加上下文。 |
None
|
返回
类型 | 描述 |
---|---|
Any
|
序列化后的对象。 |
pydantic/type_adapter.py
中的源代码
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 |
|
dump_json ¶
dump_json(
instance: T,
/,
*,
indent: int | None = None,
include: IncEx | None = None,
exclude: IncEx | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: (
bool | Literal["none", "warn", "error"]
) = True,
fallback: Callable[[Any], Any] | None = None,
serialize_as_any: bool = False,
context: dict[str, Any] | None = None,
) -> bytes
使用文档
将适配类型的实例序列化为 JSON。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
instance
|
T
|
要序列化的实例。 |
必需 |
indent
|
int | None
|
JSON 缩进的空格数。 |
None
|
include
|
IncEx | None
|
要包含的字段。 |
None
|
exclude
|
IncEx | None
|
要排除的字段。 |
None
|
by_alias
|
bool | None
|
是否对字段名称使用别名。 |
None
|
exclude_unset
|
bool
|
是否排除未设置的字段。 |
False
|
exclude_defaults
|
bool
|
是否排除具有默认值的字段。 |
False
|
exclude_none
|
bool
|
是否排除值为 |
False
|
round_trip
|
bool
|
是否序列化和反序列化实例以确保往返。 |
False
|
warnings
|
bool | Literal['none', 'warn', 'error']
|
如何处理序列化错误。 False/"none" 忽略它们,True/"warn" 记录错误,"error" 引发 |
True
|
fallback
|
Callable[[Any], Any] | None
|
遇到未知值时要调用的函数。 如果未提供,则会引发 |
None
|
serialize_as_any
|
bool
|
是否使用鸭子类型序列化行为序列化字段。 |
False
|
context
|
dict[str, Any] | None
|
要传递给序列化器的附加上下文。 |
None
|
返回
类型 | 描述 |
---|---|
bytes
|
给定实例的 JSON 表示形式(以字节为单位)。 |
pydantic/type_adapter.py
中的源代码
588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 |
|
json_schema ¶
json_schema(
*,
by_alias: bool = True,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[
GenerateJsonSchema
] = GenerateJsonSchema,
mode: JsonSchemaMode = "validation"
) -> dict[str, Any]
为适配类型生成 JSON 模式。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
by_alias
|
bool
|
是否对字段名称使用别名。 |
True
|
ref_template
|
str
|
用于生成 $ref 字符串的格式字符串。 |
DEFAULT_REF_TEMPLATE
|
schema_generator
|
type[GenerateJsonSchema]
|
用于创建模式的生成器类。 |
GenerateJsonSchema
|
mode
|
JsonSchemaMode
|
用于模式生成的模式。 |
'validation'
|
返回
类型 | 描述 |
---|---|
dict[str, Any]
|
模型的 JSON 模式,以字典形式表示。 |
pydantic/type_adapter.py
中的源代码
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 |
|
json_schemas staticmethod
¶
json_schemas(
inputs: Iterable[
tuple[
JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]
]
],
/,
*,
by_alias: bool = True,
title: str | None = None,
description: str | None = None,
ref_template: str = DEFAULT_REF_TEMPLATE,
schema_generator: type[
GenerateJsonSchema
] = GenerateJsonSchema,
) -> tuple[
dict[
tuple[JsonSchemaKeyT, JsonSchemaMode],
JsonSchemaValue,
],
JsonSchemaValue,
]
生成 JSON 模式,包括来自多个类型适配器的定义。
参数
名称 | 类型 | 描述 | 默认值 |
---|---|---|---|
inputs
|
Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]]
|
模式生成的输入。 前两项将构成(第一个)输出映射的键; 类型适配器将提供核心模式,这些模式将转换为输出 JSON 模式中的定义。 |
必需 |
by_alias
|
bool
|
是否使用别名。 |
True
|
title
|
str | None
|
模式的标题。 |
None
|
description
|
str | None
|
模式的描述。 |
None
|
ref_template
|
str
|
用于生成 $ref 字符串的格式字符串。 |
DEFAULT_REF_TEMPLATE
|
schema_generator
|
type[GenerateJsonSchema]
|
用于创建模式的生成器类。 |
GenerateJsonSchema
|
返回
类型 | 描述 |
---|---|
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]
|
一个元组,其中
|
pydantic/type_adapter.py
中的源代码
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 |
|