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 that TypeAdapter is not an actual type, so you cannot use it in type annotations.
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.
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. Returns: A type adapter configured for the specified `type`. """config_wrapper=_config.ConfigWrapper(config)try:type_has_config=issubclass(type,BaseModel)oris_dataclass(type)oris_typeddict(type)exceptTypeError:# type is not a classtype_has_config=Falseiftype_has_configandconfigisnotNone:raisePydanticUserError('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',)core_schema:CoreSchematry:core_schema=_getattr_no_parents(type,'__pydantic_core_schema__')exceptAttributeError:core_schema=_get_schema(type,config_wrapper,parent_depth=_parent_depth+1)core_config=config_wrapper.core_config(None)validator:SchemaValidatortry:validator=_getattr_no_parents(type,'__pydantic_validator__')exceptAttributeError:ifmoduleisNone:f=sys._getframe(1)module=cast(str,f.f_globals['__name__'])validator=create_schema_validator(core_schema,type,module,str(type),'TypeAdapter',core_config,config_wrapper.plugin_settings)# type: ignoreserializer:SchemaSerializertry:serializer=_getattr_no_parents(type,'__pydantic_serializer__')exceptAttributeError:serializer=SchemaSerializer(core_schema,core_config)self.core_schema=core_schemaself.validator=validatorself.serializer=serializer
defvalidate_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. """returnself.validator.validate_python(__object,strict=strict,from_attributes=from_attributes,context=context)
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
241242243244245246247248249250251252253254255256
defvalidate_json(self,__data:str|bytes,*,strict:bool|None=None,context:dict[str,Any]|None=None)->T:"""Usage docs: https://docs.pydantic.dev/2.5/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. """returnself.validator.validate_json(__data,strict=strict,context=context)
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
258259260261262263264265266267268269
defvalidate_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. """returnself.validator.validate_strings(__obj,strict=strict,context=context)
The default value wrapped in a Some if there is one or None if not.
Source code in pydantic/type_adapter.py
271272273274275276277278279280281
defget_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. """returnself.validator.get_default_value(strict=strict,context=context)
defdump_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=True,)->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: Whether to display serialization warnings. Returns: The serialized object. """returnself.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,)
defdump_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=True,)->bytes:"""Usage docs: https://docs.pydantic.dev/2.5/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: Whether to emit serialization warnings. Returns: The JSON representation of the given instance as bytes. """returnself.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,)
defjson_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)returnschema_generator_instance.generate(self.core_schema,mode=mode)
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.
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.
@staticmethoddefjson_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=[(key,mode,adapter.core_schema)forkey,mode,adapterin__inputs]json_schemas_map,definitions=schema_generator_instance.generate_definitions(inputs)json_schema:dict[str,Any]={}ifdefinitions:json_schema['$defs']=definitionsiftitle:json_schema['title']=titleifdescription:json_schema['description']=descriptionreturnjson_schemas_map,json_schema