跳转至

类型适配器

Bases: Generic[T]

Usage docs: https://pydantic.com.cn/2.9/concepts/type_adapter/

Type adapters provide a flexible way to perform validation and serialization based on a Python type.

A TypeAdapter instance exposes some of the functionality from BaseModel instance methods for types that do not have such methods (such as dataclasses, primitive types, and more).

Note: TypeAdapter instances are not types, and cannot be used as type annotations for fields.

Note: By default, TypeAdapter does not respect the defer_build=True setting in the model_config or in the TypeAdapter constructor config. You need to also explicitly set experimental_defer_build_mode=('model', 'type_adapter') of the config to defer the model validator and serializer construction. Thus, this feature is opt-in to ensure backwards compatibility.

Attributes:

Name Type Description
core_schema CoreSchema

The core schema for the type.

validator SchemaValidator

The schema validator for the type.

serializer SchemaSerializer

The schema serializer for the type.

Parameters:

Name Type Description Default
type Any

The type associated with the TypeAdapter.

required
config ConfigDict | None

Configuration for the TypeAdapter, should be a dictionary conforming to ConfigDict.

None
_parent_depth int

depth at which to search the parent namespace to construct the local namespace.

2
module str | None

The module that passes to plugin if provided.

None

Note

You cannot use the config argument when instantiating a TypeAdapter if the type you're using has its own config that cannot be overridden (ex: BaseModel, TypedDict, and dataclass). A type-adapter-config-unused error will be raised in this case.

Note

The _parent_depth argument is named with an underscore to suggest its private nature and discourage use. It may be deprecated in a minor version, so we only recommend using it if you're comfortable with potential change in behavior / support.

Compatibility with mypy

Depending on the type used, mypy might raise an error when instantiating a TypeAdapter. As a workaround, you can explicitly annotate your variable:

from typing import Union

from pydantic import TypeAdapter

ta: TypeAdapter[Union[str, int]] = TypeAdapter(Union[str, int])  # type: ignore[arg-type]

Returns:

Type Description
None

A type adapter configured for the specified type.

Source code in pydantic/type_adapter.py
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
def __init__(
    self,
    type: Any,
    *,
    config: ConfigDict | None = None,
    _parent_depth: int = 2,
    module: str | None = None,
) -> None:
    """Initializes the TypeAdapter object.

    Args:
        type: The type associated with the `TypeAdapter`.
        config: Configuration for the `TypeAdapter`, should be a dictionary conforming to [`ConfigDict`][pydantic.config.ConfigDict].
        _parent_depth: depth at which to search the parent namespace to construct the local namespace.
        module: The module that passes to plugin if provided.

    !!! note
        You cannot use the `config` argument when instantiating a `TypeAdapter` if the type you're using has its own
        config that cannot be overridden (ex: `BaseModel`, `TypedDict`, and `dataclass`). A
        [`type-adapter-config-unused`](../errors/usage_errors.md#type-adapter-config-unused) error will be raised in this case.

    !!! note
        The `_parent_depth` argument is named with an underscore to suggest its private nature and discourage use.
        It may be deprecated in a minor version, so we only recommend using it if you're
        comfortable with potential change in behavior / support.

    ??? tip "Compatibility with `mypy`"
        Depending on the type used, `mypy` might raise an error when instantiating a `TypeAdapter`. As a workaround, you can explicitly
        annotate your variable:

        ```py
        from typing import Union

        from pydantic import TypeAdapter

        ta: TypeAdapter[Union[str, int]] = TypeAdapter(Union[str, int])  # type: ignore[arg-type]
        ```

    Returns:
        A type adapter configured for the specified `type`.
    """
    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
    if module is None:
        f = sys._getframe(1)
        self._module_name = cast(str, f.f_globals.get('__name__', ''))
    else:
        self._module_name = module

    self._core_schema: CoreSchema | None = None
    self._validator: SchemaValidator | PluggableSchemaValidator | None = None
    self._serializer: SchemaSerializer | None = None

    if not self._defer_build():
        # Immediately initialize the core schema, validator and serializer
        with self._with_frame_depth(1):  # +1 frame depth for this __init__
            # Model itself may be using deferred building. For backward compatibility we don't rebuild model mocks
            # here as part of __init__ even though TypeAdapter itself is not using deferred building.
            self._init_core_attrs(rebuild_mocks=False)

core_schema cached property

core_schema: CoreSchema

The pydantic-core schema used to build the SchemaValidator and SchemaSerializer.

validator cached property

validator: SchemaValidator | PluggableSchemaValidator

The pydantic-core SchemaValidator used to validate instances of the model.

serializer cached property

serializer: SchemaSerializer

The pydantic-core SchemaSerializer used to dump instances of the model.

validate_python

validate_python(
    object: Any,
    /,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | None = None,
) -> T

Validate a Python object against the model.

Parameters:

Name Type Description Default
object Any

The Python object to validate against the model.

required
strict bool | None

Whether to strictly check types.

None
from_attributes bool | None

Whether to extract data from object attributes.

None
context dict[str, Any] | None

Additional context to pass to the validator.

None

Note

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

Returns:

Type Description
T

The validated object.

Source code in pydantic/type_adapter.py
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
@_frame_depth(1)
def validate_python(
    self,
    object: Any,
    /,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: dict[str, Any] | 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.

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

    Returns:
        The validated object.
    """
    return self.validator.validate_python(object, strict=strict, from_attributes=from_attributes, context=context)

validate_json

validate_json(
    data: str | bytes,
    /,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> T

Usage docs: https://pydantic.com.cn/2.9/concepts/json/#json-parsing

Validate a JSON string or bytes against the model.

Parameters:

Name Type Description Default
data str | bytes

The JSON data to validate against the model.

required
strict bool | None

Whether to strictly check types.

None
context dict[str, Any] | None

Additional context to use during validation.

None

Returns:

Type Description
T

The validated object.

Source code in pydantic/type_adapter.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
@_frame_depth(1)
def validate_json(
    self, data: str | bytes, /, *, strict: bool | None = None, context: dict[str, Any] | None = None
) -> T:
    """Usage docs: https://pydantic.com.cn/2.9/concepts/json/#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.

    Returns:
        The validated object.
    """
    return self.validator.validate_json(data, strict=strict, context=context)

validate_strings

validate_strings(
    obj: Any,
    /,
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> T

Validate object contains string data against the model.

Parameters:

Name Type Description Default
obj Any

The object contains string data to validate.

required
strict bool | None

Whether to strictly check types.

None
context dict[str, Any] | None

Additional context to use during validation.

None

Returns:

Type Description
T

The validated object.

Source code in pydantic/type_adapter.py
393
394
395
396
397
398
399
400
401
402
403
404
405
@_frame_depth(1)
def validate_strings(self, obj: Any, /, *, strict: bool | None = None, context: dict[str, Any] | 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.

    Returns:
        The validated object.
    """
    return self.validator.validate_strings(obj, strict=strict, context=context)

get_default_value

get_default_value(
    *,
    strict: bool | None = None,
    context: dict[str, Any] | None = None
) -> Some[T] | None

Get the default value for the wrapped type.

Parameters:

Name Type Description Default
strict bool | None

Whether to strictly check types.

None
context dict[str, Any] | None

Additional context to pass to the validator.

None

Returns:

Type Description
Some[T] | None

The default value wrapped in a Some if there is one or None if not.

Source code in pydantic/type_adapter.py
407
408
409
410
411
412
413
414
415
416
417
418
@_frame_depth(1)
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 = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: (
        bool | Literal["none", "warn", "error"]
    ) = True,
    serialize_as_any: bool = False,
    context: dict[str, Any] | None = None,
) -> Any

Dump an instance of the adapted type to a Python object.

Parameters:

Name Type Description Default
instance T

The Python object to serialize.

required
mode Literal['json', 'python']

The output format.

'python'
include IncEx | None

Fields to include in the output.

None
exclude IncEx | None

Fields to exclude from the output.

None
by_alias bool

Whether to use alias names for field names.

False
exclude_unset bool

Whether to exclude unset fields.

False
exclude_defaults bool

Whether to exclude fields with default values.

False
exclude_none bool

Whether to exclude fields with None values.

False
round_trip bool

Whether to output the serialized data in a way that is compatible with deserialization.

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

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a PydanticSerializationError.

True
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False
context dict[str, Any] | None

Additional context to pass to the serializer.

None

Returns:

Type Description
Any

The serialized object.

Source code in pydantic/type_adapter.py
420
421
422
423
424
425
426
427
428
429
430
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
@_frame_depth(1)
def dump_python(
    self,
    instance: T,
    /,
    *,
    mode: Literal['json', 'python'] = 'python',
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    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].
        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,
        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 = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: (
        bool | Literal["none", "warn", "error"]
    ) = True,
    serialize_as_any: bool = False,
    context: dict[str, Any] | None = None,
) -> bytes

Usage docs: https://pydantic.com.cn/2.9/concepts/json/#json-serialization

Serialize an instance of the adapted type to JSON.

Parameters:

Name Type Description Default
instance T

The instance to be serialized.

required
indent int | None

Number of spaces for JSON indentation.

None
include IncEx | None

Fields to include.

None
exclude IncEx | None

Fields to exclude.

None
by_alias bool

Whether to use alias names for field names.

False
exclude_unset bool

Whether to exclude unset fields.

False
exclude_defaults bool

Whether to exclude fields with default values.

False
exclude_none bool

Whether to exclude fields with a value of None.

False
round_trip bool

Whether to serialize and deserialize the instance to ensure round-tripping.

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

How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a PydanticSerializationError.

True
serialize_as_any bool

Whether to serialize fields with duck-typing serialization behavior.

False
context dict[str, Any] | None

Additional context to pass to the serializer.

None

Returns:

Type Description
bytes

The JSON representation of the given instance as bytes.

Source code in pydantic/type_adapter.py
473
474
475
476
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
519
520
521
522
523
524
525
526
@_frame_depth(1)
def dump_json(
    self,
    instance: T,
    /,
    *,
    indent: int | None = None,
    include: IncEx | None = None,
    exclude: IncEx | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal['none', 'warn', 'error'] = True,
    serialize_as_any: bool = False,
    context: dict[str, Any] | None = None,
) -> bytes:
    """Usage docs: https://pydantic.com.cn/2.9/concepts/json/#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].
        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,
        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]

Generate a JSON schema for the adapted type.

Parameters:

Name Type Description Default
by_alias bool

Whether to use alias names for field names.

True
ref_template str

The format string used for generating $ref strings.

DEFAULT_REF_TEMPLATE
schema_generator type[GenerateJsonSchema]

The generator class used for creating the schema.

GenerateJsonSchema
mode JsonSchemaMode

The mode to use for schema generation.

'validation'

Returns:

Type Description
dict[str, Any]

The JSON schema for the model as a dictionary.

Source code in pydantic/type_adapter.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
@_frame_depth(1)
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)
    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,
]

Generate a JSON schema including definitions from multiple type adapters.

Parameters:

Name Type Description Default
inputs Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, TypeAdapter[Any]]]

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.

required
by_alias bool

Whether to use alias names.

True
title str | None

The title for the schema.

None
description str | None

The description for the schema.

None
ref_template str

The format string used for generating $ref strings.

DEFAULT_REF_TEMPLATE
schema_generator type[GenerateJsonSchema]

The generator class used for creating the schema.

GenerateJsonSchema

Returns:

Type Description
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]

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.
Source code in pydantic/type_adapter.py
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
@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:
        with adapter._with_frame_depth(1):  # +1 for json_schemas staticmethod
            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

本文总阅读量