Skip to content
You're viewing docs for v2.5. See the latest version →

TypeAdapter

TypeAdapter

Bases: Generic[T]

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.

Attributes

core_schema

Default: core_schema

validator

Default: validator

serializer

Default: serializer

Methods

new

def __new__(cls, __type: type[T], config: ConfigDict | None = ...) -> TypeAdapter[T]
def __new__(cls, __type: T, config: ConfigDict | None = ...) -> TypeAdapter[T]

A class representing the type adapter.

Returns

TypeAdapter[T]

init

def __init__(
    type: type[T],
    config: ConfigDict | None = None,
    _parent_depth: int = 2,
    module: str | None = None,
) -> None
def __init__(
    type: T,
    config: ConfigDict | None = None,
    _parent_depth: int = 2,
    module: str | None = None,
) -> None

Initializes the TypeAdapter object.

Returns

None — A type adapter configured for the specified type.

Parameters

type : Any

The type associated with the TypeAdapter.

config : ConfigDict | None Default: None

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

_parent_depth : int Default: 2

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

module : str | None Default: None

The module that passes to plugin if provided.

validate_python

def 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.

Returns

T — The validated object.

Parameters

__object : Any

The Python object to validate against the model.

strict : bool | None Default: None

Whether to strictly check types.

from_attributes : bool | None Default: None

Whether to extract data from object attributes.

context : dict[str, Any] | None Default: None

Additional context to pass to the validator.

validate_json

def validate_json(
    __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.

Returns

T — The validated object.

Parameters

__data : str | bytes

The JSON data to validate against the model.

strict : bool | None Default: None

Whether to strictly check types.

context : dict[str, Any] | None Default: None

Additional context to use during validation.

validate_strings

def validate_strings(
    __obj: Any,
    strict: bool | None = None,
    context: dict[str, Any] | None = None,
) -> T

Validate object contains string data against the model.

Returns

T — The validated object.

Parameters

__obj : Any

The object contains string data to validate.

strict : bool | None Default: None

Whether to strictly check types.

context : dict[str, Any] | None Default: None

Additional context to use during validation.

get_default_value

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

Get the default value for the wrapped type.

Returns

Some[T] | None — The default value wrapped in a Some if there is one or None if not.

Parameters

strict : bool | None Default: None

Whether to strictly check types.

context : dict[str, Any] | None Default: None

Additional context to pass to the validator.

dump_python

def 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 = True,
) -> Any

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

Returns

Any — The serialized object.

Parameters

__instance : T

The Python object to serialize.

mode : Literal['json', 'python'] Default: 'python'

The output format.

include : IncEx | None Default: None

Fields to include in the output.

exclude : IncEx | None Default: None

Fields to exclude from the output.

by_alias : bool Default: False

Whether to use alias names for field names.

exclude_unset : bool Default: False

Whether to exclude unset fields.

exclude_defaults : bool Default: False

Whether to exclude fields with default values.

exclude_none : bool Default: False

Whether to exclude fields with None values.

round_trip : bool Default: False

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

warnings : bool Default: True

Whether to display serialization warnings.

dump_json

def 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 = True,
) -> bytes

Usage docs: https://docs.pydantic.dev/2.5/concepts/json/#json-serialization

Serialize an instance of the adapted type to JSON.

Returns

bytes — The JSON representation of the given instance as bytes.

Parameters

__instance : T

The instance to be serialized.

indent : int | None Default: None

Number of spaces for JSON indentation.

include : IncEx | None Default: None

Fields to include.

exclude : IncEx | None Default: None

Fields to exclude.

by_alias : bool Default: False

Whether to use alias names for field names.

exclude_unset : bool Default: False

Whether to exclude unset fields.

exclude_defaults : bool Default: False

Whether to exclude fields with default values.

exclude_none : bool Default: False

Whether to exclude fields with a value of None.

round_trip : bool Default: False

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

warnings : bool Default: True

Whether to emit serialization warnings.

json_schema

def 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.

Returns

dict[str, Any] — The JSON schema for the model as a dictionary.

Parameters

by_alias : bool Default: True

Whether to use alias names for field names.

ref_template : str Default: DEFAULT_REF_TEMPLATE

The format string used for generating $ref strings.

schema_generator : type[GenerateJsonSchema] Default: GenerateJsonSchema

The generator class used for creating the schema.

mode : JsonSchemaMode Default: 'validation'

The mode to use for schema generation.

json_schemas

@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.

Returns

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.
Parameters

__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.

by_alias : bool Default: True

Whether to use alias names.

title : str | None Default: None

The title for the schema.

description : str | None Default: None

The description for the schema.

ref_template : str Default: DEFAULT_REF_TEMPLATE

The format string used for generating $ref strings.

schema_generator : type[GenerateJsonSchema] Default: GenerateJsonSchema

The generator class used for creating the schema.