跳到内容

TypeAdapter

基类:Generic[T]

使用文档

TypeAdapter

类型适配器提供了一种灵活的方式,可以基于 Python 类型执行验证和序列化。

TypeAdapter 实例公开了 BaseModel 实例方法的一些功能,用于不具备这些方法的类型(例如数据类、原始类型等)。

注意: TypeAdapter 实例不是类型,不能用作字段的类型注解。

参数

名称 类型 描述 默认值
type Any

TypeAdapter 关联的类型。

必需
config ConfigDict | None

TypeAdapter 的配置,应为符合 ConfigDict 的字典。

注意

如果正在使用的类型有自己的不可覆盖的配置(例如:BaseModelTypedDictdataclass),则在实例化 TypeAdapter 时无法提供配置。 在这种情况下,会引发 type-adapter-config-unused 错误。

None
_parent_depth int

搜索 父框架 的深度。 此框架在模式构建期间解析前向注解时使用,方法是查找此框架的全局变量和局部变量。 默认为 2,这将导致 TypeAdapter 实例化的框架。

注意

此参数以带下划线的方式命名,以暗示其私有性质并劝阻使用。 它可能会在次要版本中被弃用,因此我们仅建议在您对行为/支持的潜在更改感到满意的情况下使用它。 它的默认值为 2,因为在内部,TypeAdapter 类会再次调用以获取框架。

2
module str | None

如果提供,则传递给插件的模块。

None

属性

名称 类型 描述
core_schema CoreSchema

类型的核心模式。

validator SchemaValidator | PluggableSchemaValidator

类型的模式验证器。

serializer SchemaSerializer

类型的模式序列化器。

pydantic_complete bool

类型核心模式是否成功构建。

mypy 的兼容性

根据使用的类型,实例化 TypeAdaptermypy 可能会引发错误。 作为一种解决方法,您可以显式注解您的变量

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 的源代码。

这适用于在此函数在模块中调用的情况,该模块在其作用域中具有前向引用的目标,但并非始终适用于更复杂的情况。

例如,以下列代码为例

a.py
IntList = list[int]
OuterDict = dict[str, 'IntList']
b.py
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

如果 OuterDictBaseModel,这将起作用,因为它会在 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
def __init__(
    self,
    type: Any,
    *,
    config: ConfigDict | None = None,
    _parent_depth: int = 2,
    module: str | None = None,
) -> None:
    if _type_has_config(type) and config is not None:
        raise PydanticUserError(
            'Cannot use `config` when the type is a BaseModel, dataclass or TypedDict.'
            ' These types can have their own config and setting the config via the `config`'
            ' parameter to TypeAdapter will not override it, thus the `config` you passed to'
            ' TypeAdapter becomes meaningless, which is probably not what you want.',
            code='type-adapter-config-unused',
        )

    self._type = type
    self._config = config
    self._parent_depth = _parent_depth
    self.pydantic_complete = False

    parent_frame = self._fetch_parent_frame()
    if parent_frame is not None:
        globalns = parent_frame.f_globals
        # Do not provide a local ns if the type adapter happens to be instantiated at the module level:
        localns = parent_frame.f_locals if parent_frame.f_locals is not globalns else {}
    else:
        globalns = {}
        localns = {}

    self._module_name = module or cast(str, globalns.get('__name__', ''))
    self._init_core_attrs(
        ns_resolver=_namespace_utils.NsResolver(
            namespaces_tuple=_namespace_utils.NamespacesTuple(locals=localns, globals=globalns),
            parent_namespace=localns,
        ),
        force=False,
    )

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

False
raise_errors bool

是否引发错误,默认为 True

True
_parent_namespace_depth int

搜索 父框架 的深度。 此框架在模式重建期间解析前向注解时使用,方法是查找此框架的局部变量。 默认为 2,这将导致调用该方法的框架。

2
_types_namespace MappingNamespace | None

要使用的显式类型命名空间,而不是使用父框架中的本地命名空间。 默认为 None

None

返回

类型 描述
bool | None

如果模式已“完整”且不需要重建,则返回 None

bool | None

如果需要重建,则重建成功返回 True,否则返回 False

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
def rebuild(
    self,
    *,
    force: bool = False,
    raise_errors: bool = True,
    _parent_namespace_depth: int = 2,
    _types_namespace: _namespace_utils.MappingNamespace | None = None,
) -> bool | None:
    """Try to rebuild the pydantic-core schema for the adapter's type.

    This may be necessary when one of the annotations is a ForwardRef which could not be resolved during
    the initial attempt to build the schema, and automatic rebuilding fails.

    Args:
        force: Whether to force the rebuilding of the type adapter's schema, defaults to `False`.
        raise_errors: Whether to raise errors, defaults to `True`.
        _parent_namespace_depth: Depth at which to search for the [parent frame][frame-objects]. This
            frame is used when resolving forward annotations during schema rebuilding, by looking for
            the locals of this frame. Defaults to 2, which will result in the frame where the method
            was called.
        _types_namespace: An explicit types namespace to use, instead of using the local namespace
            from the parent frame. Defaults to `None`.

    Returns:
        Returns `None` if the schema is already "complete" and rebuilding was not required.
        If rebuilding _was_ required, returns `True` if rebuilding was successful, otherwise `False`.
    """
    if not force and self.pydantic_complete:
        return None

    if _types_namespace is not None:
        rebuild_ns = _types_namespace
    elif _parent_namespace_depth > 0:
        rebuild_ns = _typing_extra.parent_frame_namespace(parent_depth=_parent_namespace_depth, force=True) or {}
    else:
        rebuild_ns = {}

    # we have to manually fetch globals here because there's no type on the stack of the NsResolver
    # and so we skip the globalns = get_module_ns_of(typ) call that would normally happen
    globalns = sys._getframe(max(_parent_namespace_depth - 1, 1)).f_globals
    ns_resolver = _namespace_utils.NsResolver(
        namespaces_tuple=_namespace_utils.NamespacesTuple(locals=rebuild_ns, globals=globalns),
        parent_namespace=rebuild_ns,
    )
    return self._init_core_attrs(ns_resolver=ns_resolver, force=True, raise_errors=raise_errors)

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
def validate_python(
    self,
    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:
    """Validate a Python object against the model.

    Args:
        object: The Python object to validate against the model.
        strict: Whether to strictly check types.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.
        experimental_allow_partial: **Experimental** whether to enable
            [partial validation](../concepts/experimental.md#partial-validation), e.g. to process streams.
            * False / 'off': Default behavior, no partial validation.
            * True / 'on': Enable partial validation.
            * 'trailing-strings': Enable partial validation and allow trailing strings in the input.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    !!! note
        When using `TypeAdapter` with a Pydantic `dataclass`, the use of the `from_attributes`
        argument is not supported.

    Returns:
        The validated object.
    """
    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return self.validator.validate_python(
        object,
        strict=strict,
        from_attributes=from_attributes,
        context=context,
        allow_partial=experimental_allow_partial,
        by_alias=by_alias,
        by_name=by_name,
    )

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 解析

根据模型验证 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
def validate_json(
    self,
    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:
    """!!! abstract "Usage Documentation"
        [JSON Parsing](../concepts/json.md#json-parsing)

    Validate a JSON string or bytes against the model.

    Args:
        data: The JSON data to validate against the model.
        strict: Whether to strictly check types.
        context: Additional context to use during validation.
        experimental_allow_partial: **Experimental** whether to enable
            [partial validation](../concepts/experimental.md#partial-validation), e.g. to process streams.
            * False / 'off': Default behavior, no partial validation.
            * True / 'on': Enable partial validation.
            * 'trailing-strings': Enable partial validation and allow trailing strings in the input.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated object.
    """
    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return self.validator.validate_json(
        data,
        strict=strict,
        context=context,
        allow_partial=experimental_allow_partial,
        by_alias=by_alias,
        by_name=by_name,
    )

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
def validate_strings(
    self,
    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:
    """Validate object contains string data against the model.

    Args:
        obj: The object contains string data to validate.
        strict: Whether to strictly check types.
        context: Additional context to use during validation.
        experimental_allow_partial: **Experimental** whether to enable
            [partial validation](../concepts/experimental.md#partial-validation), e.g. to process streams.
            * False / 'off': Default behavior, no partial validation.
            * True / 'on': Enable partial validation.
            * 'trailing-strings': Enable partial validation and allow trailing strings in the input.
        by_alias: Whether to use the field's alias when validating against the provided input data.
        by_name: Whether to use the field's name when validating against the provided input data.

    Returns:
        The validated object.
    """
    if by_alias is False and by_name is not True:
        raise PydanticUserError(
            'At least one of `by_alias` or `by_name` must be set to True.',
            code='validate-by-alias-and-name-false',
        )

    return self.validator.validate_strings(
        obj,
        strict=strict,
        context=context,
        allow_partial=experimental_allow_partial,
        by_alias=by_alias,
        by_name=by_name,
    )

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

默认值,如果存在则包装在 Some 中,否则为 None。

pydantic/type_adapter.py 中的源代码
520
521
522
523
524
525
526
527
528
529
530
def get_default_value(self, *, strict: bool | None = None, context: dict[str, Any] | None = None) -> Some[T] | None:
    """Get the default value for the wrapped type.

    Args:
        strict: Whether to strictly check types.
        context: Additional context to pass to the validator.

    Returns:
        The default value wrapped in a `Some` if there is one or None if not.
    """
    return self.validator.get_default_value(strict=strict, context=context)

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" 引发 PydanticSerializationError

True
fallback Callable[[Any], Any] | None

遇到未知值时要调用的函数。 如果未提供,则会引发 PydanticSerializationError 错误。

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
def dump_python(
    self,
    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:
    """Dump an instance of the adapted type to a Python object.

    Args:
        instance: The Python object to serialize.
        mode: The output format.
        include: Fields to include in the output.
        exclude: Fields to exclude from the output.
        by_alias: Whether to use alias names for field names.
        exclude_unset: Whether to exclude unset fields.
        exclude_defaults: Whether to exclude fields with default values.
        exclude_none: Whether to exclude fields with None values.
        round_trip: Whether to output the serialized data in a way that is compatible with deserialization.
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
        context: Additional context to pass to the serializer.

    Returns:
        The serialized object.
    """
    return self.serializer.to_python(
        instance,
        mode=mode,
        by_alias=by_alias,
        include=include,
        exclude=exclude,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
        context=context,
    )

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 序列化

将适配类型的实例序列化为 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

是否排除值为 None 的字段。

False
round_trip bool

是否序列化和反序列化实例以确保往返。

False
warnings bool | Literal['none', 'warn', 'error']

如何处理序列化错误。 False/"none" 忽略它们,True/"warn" 记录错误,"error" 引发 PydanticSerializationError

True
fallback Callable[[Any], Any] | None

遇到未知值时要调用的函数。 如果未提供,则会引发 PydanticSerializationError 错误。

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
def dump_json(
    self,
    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:
    """!!! abstract "Usage Documentation"
        [JSON Serialization](../concepts/json.md#json-serialization)

    Serialize an instance of the adapted type to JSON.

    Args:
        instance: The instance to be serialized.
        indent: Number of spaces for JSON indentation.
        include: Fields to include.
        exclude: Fields to exclude.
        by_alias: Whether to use alias names for field names.
        exclude_unset: Whether to exclude unset fields.
        exclude_defaults: Whether to exclude fields with default values.
        exclude_none: Whether to exclude fields with a value of `None`.
        round_trip: Whether to serialize and deserialize the instance to ensure round-tripping.
        warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors,
            "error" raises a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        fallback: A function to call when an unknown value is encountered. If not provided,
            a [`PydanticSerializationError`][pydantic_core.PydanticSerializationError] error is raised.
        serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.
        context: Additional context to pass to the serializer.

    Returns:
        The JSON representation of the given instance as bytes.
    """
    return self.serializer.to_json(
        instance,
        indent=indent,
        include=include,
        exclude=exclude,
        by_alias=by_alias,
        exclude_unset=exclude_unset,
        exclude_defaults=exclude_defaults,
        exclude_none=exclude_none,
        round_trip=round_trip,
        warnings=warnings,
        fallback=fallback,
        serialize_as_any=serialize_as_any,
        context=context,
    )

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
def json_schema(
    self,
    *,
    by_alias: bool = True,
    ref_template: str = DEFAULT_REF_TEMPLATE,
    schema_generator: type[GenerateJsonSchema] = GenerateJsonSchema,
    mode: JsonSchemaMode = 'validation',
) -> dict[str, Any]:
    """Generate a JSON schema for the adapted type.

    Args:
        by_alias: Whether to use alias names for field names.
        ref_template: The format string used for generating $ref strings.
        schema_generator: The generator class used for creating the schema.
        mode: The mode to use for schema generation.

    Returns:
        The JSON schema for the model as a dictionary.
    """
    schema_generator_instance = schema_generator(by_alias=by_alias, ref_template=ref_template)
    if isinstance(self.core_schema, _mock_val_ser.MockCoreSchema):
        self.core_schema.rebuild()
        assert not isinstance(self.core_schema, _mock_val_ser.MockCoreSchema), 'this is a bug! please report it'
    return schema_generator_instance.generate(self.core_schema, mode=mode)

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]

一个元组,其中

  • 第一个元素是一个字典,其键是 JSON 模式键类型和 JSON 模式的元组,其值是与该输入对对应的 JSON 模式。 (这些模式可能具有对第二个返回元素中定义的定义的 JsonRef 引用。)
  • 第二个元素是一个 JSON 模式,其中包含第一个返回元素中引用的所有定义,以及可选的标题和描述键。
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
@staticmethod
def 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]:
    """Generate a JSON schema including definitions from multiple type adapters.

    Args:
        inputs: Inputs to schema generation. The first two items will form the keys of the (first)
            output mapping; the type adapters will provide the core schemas that get converted into
            definitions in the output JSON schema.
        by_alias: Whether to use alias names.
        title: The title for the schema.
        description: The description for the schema.
        ref_template: The format string used for generating $ref strings.
        schema_generator: The generator class used for creating the schema.

    Returns:
        A tuple where:

            - The first element is a dictionary whose keys are tuples of JSON schema key type and JSON mode, and
                whose values are the JSON schema corresponding to that pair of inputs. (These schemas may have
                JsonRef references to definitions that are defined in the second returned element.)
            - The second element is a JSON schema containing all definitions referenced in the first returned
                element, along with the optional title and description keys.

    """
    schema_generator_instance = schema_generator(by_alias=by_alias, ref_template=ref_template)

    inputs_ = []
    for key, mode, adapter in inputs:
        # This is the same pattern we follow for model json schemas - we attempt a core schema rebuild if we detect a mock
        if isinstance(adapter.core_schema, _mock_val_ser.MockCoreSchema):
            adapter.core_schema.rebuild()
            assert not isinstance(adapter.core_schema, _mock_val_ser.MockCoreSchema), (
                'this is a bug! please report it'
            )
        inputs_.append((key, mode, adapter.core_schema))

    json_schemas_map, definitions = schema_generator_instance.generate_definitions(inputs_)

    json_schema: dict[str, Any] = {}
    if definitions:
        json_schema['$defs'] = definitions
    if title:
        json_schema['title'] = title
    if description:
        json_schema['description'] = description

    return json_schemas_map, json_schema