TypeAdapter
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).
Attributes
| Attribute | Type | Description |
|---|---|---|
| core_schema | CoreSchema | The core schema for the type. |
| validator | `SchemaValidator | PluggableSchemaValidator` |
| serializer | [SchemaSerializer](../../../serializers/mod/schemaserializer.md?sid=serializers_mod_schemaserializer) | The schema serializer for the type. |
| pydantic_complete | bool | Whether the core schema for the type is successfully built. |
Constructor
Signature
def TypeAdapter(
type: Any,
config: ConfigDict | None = None,
_parent_depth: int = 2,
module: str | None = None
) - > None
Parameters
| Name | Type | Description |
|---|---|---|
| type | Any | The Python type or special form (like Union or Annotated) associated with the TypeAdapter. |
| config | `ConfigDict | None` = None |
| _parent_depth | int = 2 | The depth used to search for the parent frame to resolve forward annotations. |
| module | `str | None` = None |
Methods
rebuild()
@classmethod
def rebuild(
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.
Parameters
| Name | Type | Description |
|---|---|---|
| force | bool = False | Whether to force the rebuilding of the type adapter's schema. |
| raise_errors | bool = True | Whether to raise errors during the rebuilding process. |
| _parent_namespace_depth | int = 2 | Depth at which to search for the parent frame to resolve forward annotations. |
| _types_namespace | `_namespace_utils.MappingNamespace | None` = None |
Returns
| Type | Description |
|---|---|
| `bool | None` |
validate_python()
@classmethod
def validate_python(
object: Any,
strict: bool | None,
extra: ExtraValues | None,
from_attributes: bool | None,
context: Any | None,
experimental_allow_partial: bool | Literal['off', 'on', 'trailing-strings'],
by_alias: bool | None,
by_name: bool | None
) - > T
Validate a Python object against the model.
Parameters
| Name | Type | Description |
|---|---|---|
| object | Any | The Python object to validate against the model. |
| strict | `bool | None` |
| extra | `ExtraValues | None` |
| from_attributes | `bool | None` |
| context | `Any | None` |
| experimental_allow_partial | `bool | Literal['off', 'on', 'trailing-strings']` |
| by_alias | `bool | None` |
| by_name | `bool | None` |
Returns
| Type | Description |
|---|---|
T | The validated object. |
validate_json()
@classmethod
def validate_json(
data: str | bytes | bytearray,
strict: bool | None,
extra: ExtraValues | None,
context: Any | None,
experimental_allow_partial: bool | Literal['off', 'on', 'trailing-strings'],
by_alias: bool | None,
by_name: bool | None
) - > T
Validate a JSON string or bytes against the model.
Parameters
| Name | Type | Description |
|---|---|---|
| data | `str | bytes |
| strict | `bool | None` |
| extra | `ExtraValues | None` |
| context | `Any | None` |
| experimental_allow_partial | `bool | Literal['off', 'on', 'trailing-strings']` |
| by_alias | `bool | None` |
| by_name | `bool | None` |
Returns
| Type | Description |
|---|---|
T | The validated object. |
validate_strings()
@classmethod
def validate_strings(
obj: Any,
strict: bool | None,
extra: ExtraValues | None,
context: Any | None,
experimental_allow_partial: bool | Literal['off', 'on', 'trailing-strings'],
by_alias: bool | None,
by_name: bool | None
) - > T
Validate object contains string data against the model.
Parameters
| Name | Type | Description |
|---|---|---|
| obj | Any | The object contains string data to validate. |
| strict | `bool | None` |
| extra | `ExtraValues | None` |
| context | `Any | None` |
| experimental_allow_partial | `bool | Literal['off', 'on', 'trailing-strings']` |
| by_alias | `bool | None` |
| by_name | `bool | None` |
Returns
| Type | Description |
|---|---|
T | The validated object. |
get_default_value()
@classmethod
def get_default_value(
strict: bool | None,
context: Any | None
) - > [Some](../../core/pydantic/core/some.md?sid=pydantic_core__pydantic_core_some)[T]| None
Get the default value for the wrapped type.
Parameters
| Name | Type | Description |
|---|---|---|
| strict | `bool | None` |
| context | `Any | None` |
Returns
| Type | Description |
|---|---|
| `Some[T] | None` |
dump_python()
@classmethod
def dump_python(
instance: T,
mode: Literal['json', 'python'],
include: IncEx | None,
exclude: IncEx | None,
by_alias: bool | None,
exclude_unset: bool,
exclude_defaults: bool,
exclude_none: bool,
exclude_computed_fields: bool,
round_trip: bool,
warnings: bool | Literal['none', 'warn', 'error'],
fallback: Callable[[Any], Any]| None,
serialize_as_any: bool,
polymorphic_serialization: bool | None,
context: Any | None
) - > Any
Dump an instance of the adapted type to a Python object.
Parameters
| Name | Type | Description |
|---|---|---|
| instance | T | The Python object to serialize. |
| mode | Literal['json', 'python'] | The output format. |
| include | `IncEx | None` |
| exclude | `IncEx | None` |
| by_alias | `bool | None` |
| exclude_unset | bool | Whether to exclude unset fields. |
| exclude_defaults | bool | Whether to exclude fields with default values. |
| exclude_none | bool | Whether to exclude fields with None values. |
| exclude_computed_fields | bool | Whether to exclude computed fields. |
| round_trip | bool | Whether to output serialized data compatible with deserialization. |
| warnings | `bool | Literal['none', 'warn', 'error']` |
| fallback | `Callable[[Any], Any] | None` |
| serialize_as_any | bool | Whether to serialize fields with duck-typing serialization behavior. |
| polymorphic_serialization | `bool | None` |
| context | `Any | None` |
Returns
| Type | Description |
|---|---|
Any | The serialized object. |
dump_json()
@classmethod
def dump_json(
instance: T,
indent: int | None,
ensure_ascii: bool,
include: IncEx | None,
exclude: IncEx | None,
by_alias: bool | None,
exclude_unset: bool,
exclude_defaults: bool,
exclude_none: bool,
exclude_computed_fields: bool,
round_trip: bool,
warnings: bool | Literal['none', 'warn', 'error'],
fallback: Callable[[Any], Any]| None,
serialize_as_any: bool,
polymorphic_serialization: bool | None,
context: Any | None
) - > bytes
Serialize an instance of the adapted type to JSON.
Parameters
| Name | Type | Description |
|---|---|---|
| instance | T | The instance to be serialized. |
| indent | `int | None` |
| ensure_ascii | bool | If True, non-ASCII characters are escaped in the output. |
| include | `IncEx | None` |
| exclude | `IncEx | None` |
| by_alias | `bool | None` |
| exclude_unset | bool | Whether to exclude unset fields. |
| exclude_defaults | bool | Whether to exclude fields with default values. |
| exclude_none | bool | Whether to exclude fields with a value of None. |
| exclude_computed_fields | bool | Whether to exclude computed fields. |
| round_trip | bool | Whether to serialize and deserialize the instance to ensure round-tripping. |
| warnings | `bool | Literal['none', 'warn', 'error']` |
| fallback | `Callable[[Any], Any] | None` |
| serialize_as_any | bool | Whether to serialize fields with duck-typing serialization behavior. |
| polymorphic_serialization | `bool | None` |
| context | `Any | None` |
Returns
| Type | Description |
|---|---|
bytes | The JSON representation of the given instance as bytes. |
json_schema()
@classmethod
def json_schema(
by_alias: bool,
ref_template: str,
union_format: Literal['any_of', 'primitive_type_array'],
schema_generator: type[[GenerateJsonSchema](../../json/schema/generatejsonschema.md?sid=pydantic_json_schema_generatejsonschema)],
mode: JsonSchemaMode
) - > dict[str, Any]
Generate a JSON schema for the adapted type.
Parameters
| Name | Type | Description |
|---|---|---|
| by_alias | bool | Whether to use alias names for field names. |
| ref_template | str | The format string used for generating $ref strings. |
| union_format | Literal['any_of', 'primitive_type_array'] | The format to use when combining schemas from unions together. |
| schema_generator | type[[GenerateJsonSchema](../../json/schema/generatejsonschema.md?sid=pydantic_json_schema_generatejsonschema)] | The generator class used for creating the schema. |
| mode | JsonSchemaMode | The mode in which to generate the schema. |
Returns
| Type | Description |
|---|---|
dict[str, Any] | The JSON schema for the model as a dictionary. |
json_schemas()
@classmethod
def json_schemas(
inputs: Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, [TypeAdapter](typeadapter.md?sid=pydantic_type_adapter_typeadapter)[Any]]],
by_alias: bool,
title: str | None,
description: str | None,
ref_template: str,
union_format: Literal['any_of', 'primitive_type_array'],
schema_generator: type[[GenerateJsonSchema](../../json/schema/generatejsonschema.md?sid=pydantic_json_schema_generatejsonschema)]
) - > tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]
Generate a JSON schema including definitions from multiple type adapters.
Parameters
| Name | Type | Description |
|---|---|---|
| inputs | Iterable[tuple[JsonSchemaKeyT, JsonSchemaMode, [TypeAdapter](typeadapter.md?sid=pydantic_type_adapter_typeadapter)[Any]]] | Inputs to schema generation containing keys, modes, and adapters. |
| by_alias | bool | Whether to use alias names. |
| title | `str | None` |
| description | `str | None` |
| ref_template | str | The format string used for generating $ref strings. |
| union_format | Literal['any_of', 'primitive_type_array'] | The format to use when combining schemas from unions together. |
| schema_generator | type[[GenerateJsonSchema](../../json/schema/generatejsonschema.md?sid=pydantic_json_schema_generatejsonschema)] | The generator class used for creating the schema. |
Returns
| Type | Description |
|---|---|
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue] | A tuple containing a mapping of input keys to schemas and a shared definitions schema. |