Skip to main content

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

AttributeTypeDescription
core_schemaCoreSchemaThe core schema for the type.
validator`SchemaValidatorPluggableSchemaValidator`
serializer[SchemaSerializer](../../../serializers/mod/schemaserializer.md?sid=serializers_mod_schemaserializer)The schema serializer for the type.
pydantic_completeboolWhether 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

NameTypeDescription
typeAnyThe Python type or special form (like Union or Annotated) associated with the TypeAdapter.
config`ConfigDictNone` = None
_parent_depthint = 2The depth used to search for the parent frame to resolve forward annotations.
module`strNone` = 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

NameTypeDescription
forcebool = FalseWhether to force the rebuilding of the type adapter's schema.
raise_errorsbool = TrueWhether to raise errors during the rebuilding process.
_parent_namespace_depthint = 2Depth at which to search for the parent frame to resolve forward annotations.
_types_namespace`_namespace_utils.MappingNamespaceNone` = None

Returns

TypeDescription
`boolNone`

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

NameTypeDescription
objectAnyThe Python object to validate against the model.
strict`boolNone`
extra`ExtraValuesNone`
from_attributes`boolNone`
context`AnyNone`
experimental_allow_partial`boolLiteral['off', 'on', 'trailing-strings']`
by_alias`boolNone`
by_name`boolNone`

Returns

TypeDescription
TThe 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

NameTypeDescription
data`strbytes
strict`boolNone`
extra`ExtraValuesNone`
context`AnyNone`
experimental_allow_partial`boolLiteral['off', 'on', 'trailing-strings']`
by_alias`boolNone`
by_name`boolNone`

Returns

TypeDescription
TThe 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

NameTypeDescription
objAnyThe object contains string data to validate.
strict`boolNone`
extra`ExtraValuesNone`
context`AnyNone`
experimental_allow_partial`boolLiteral['off', 'on', 'trailing-strings']`
by_alias`boolNone`
by_name`boolNone`

Returns

TypeDescription
TThe 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

NameTypeDescription
strict`boolNone`
context`AnyNone`

Returns

TypeDescription
`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

NameTypeDescription
instanceTThe Python object to serialize.
modeLiteral['json', 'python']The output format.
include`IncExNone`
exclude`IncExNone`
by_alias`boolNone`
exclude_unsetboolWhether to exclude unset fields.
exclude_defaultsboolWhether to exclude fields with default values.
exclude_noneboolWhether to exclude fields with None values.
exclude_computed_fieldsboolWhether to exclude computed fields.
round_tripboolWhether to output serialized data compatible with deserialization.
warnings`boolLiteral['none', 'warn', 'error']`
fallback`Callable[[Any], Any]None`
serialize_as_anyboolWhether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization`boolNone`
context`AnyNone`

Returns

TypeDescription
AnyThe 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

NameTypeDescription
instanceTThe instance to be serialized.
indent`intNone`
ensure_asciiboolIf True, non-ASCII characters are escaped in the output.
include`IncExNone`
exclude`IncExNone`
by_alias`boolNone`
exclude_unsetboolWhether to exclude unset fields.
exclude_defaultsboolWhether to exclude fields with default values.
exclude_noneboolWhether to exclude fields with a value of None.
exclude_computed_fieldsboolWhether to exclude computed fields.
round_tripboolWhether to serialize and deserialize the instance to ensure round-tripping.
warnings`boolLiteral['none', 'warn', 'error']`
fallback`Callable[[Any], Any]None`
serialize_as_anyboolWhether to serialize fields with duck-typing serialization behavior.
polymorphic_serialization`boolNone`
context`AnyNone`

Returns

TypeDescription
bytesThe 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

NameTypeDescription
by_aliasboolWhether to use alias names for field names.
ref_templatestrThe format string used for generating $ref strings.
union_formatLiteral['any_of', 'primitive_type_array']The format to use when combining schemas from unions together.
schema_generatortype[[GenerateJsonSchema](../../json/schema/generatejsonschema.md?sid=pydantic_json_schema_generatejsonschema)]The generator class used for creating the schema.
modeJsonSchemaModeThe mode in which to generate the schema.

Returns

TypeDescription
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

NameTypeDescription
inputsIterable[tuple[JsonSchemaKeyT, JsonSchemaMode, [TypeAdapter](typeadapter.md?sid=pydantic_type_adapter_typeadapter)[Any]]]Inputs to schema generation containing keys, modes, and adapters.
by_aliasboolWhether to use alias names.
title`strNone`
description`strNone`
ref_templatestrThe format string used for generating $ref strings.
union_formatLiteral['any_of', 'primitive_type_array']The format to use when combining schemas from unions together.
schema_generatortype[[GenerateJsonSchema](../../json/schema/generatejsonschema.md?sid=pydantic_json_schema_generatejsonschema)]The generator class used for creating the schema.

Returns

TypeDescription
tuple[dict[tuple[JsonSchemaKeyT, JsonSchemaMode], JsonSchemaValue], JsonSchemaValue]A tuple containing a mapping of input keys to schemas and a shared definitions schema.