new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Pydantic · API reference · all subjects

typeadapter

24 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

TypeAdapter class definition and purpose

TypeAdapter is a Pydantic class used to validate, serialize, and work with Python types that are not Pydantic models. It provides a way to apply Pydantic validation to arbitrary types like lists, dicts, or other Python objects that don't inherit from BaseModel.

TypeAdapter initialization parameters

TypeAdapter accepts a type argument specifying the Python type to validate against. It can also accept a config parameter for validation configuration, and a serializer parameter for custom serialization behavior.

TypeAdapter validation methods

TypeAdapter provides the validate_python() method to validate Python objects against the specified type, and the validate_json() method to validate JSON data.

TypeAdapter serialization methods

TypeAdapter provides the dump_python() method to serialize validated objects to Python types, and the dump_json() method to serialize to JSON bytes or strings.

TypeAdapter json_schema method

TypeAdapter provides a json_schema() method to generate a JSON schema representation of the specified type.

TypeAdapter purpose and use cases

TypeAdapter is used for type validation, serialization, and JSON schema generation without needing to create a BaseModel. It is useful when you have types that are not BaseModels that you want to validate data against, or when you want to validate a list[SomeModel] or dump it to JSON.

TypeAdapter exposes BaseModel instance methods

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.

TypeAdapter.validate_python method

TypeAdapter has a validate_python method that can be used to apply parsing logic to populate Pydantic models in a more ad-hoc way. This method behaves similarly to BaseModel.model_validate, but works with arbitrary Pydantic-compatible types.

TypeAdapter.dump_json returns bytes

TypeAdapter's dump_json method returns a bytes object, unlike the corresponding method for BaseModel, model_dump_json, which returns a str. This behavior is retained for backwards compatibility with V1.

TypeAdapter validation error handling

A TypeAdapter raises the same structured errors as a model, so tooling that records validation failures in production, such as Logfire, captures these too.

TypeAdapter parsing with list example

TypeAdapter can be used with list types. Example: user_list_adapter = TypeAdapter(list[User]) followed by user_list_adapter.validate_python([{'name': 'Fred', 'id': '3'}]) parses a list of dictionaries into the specified list type.

TypeAdapter parsing BaseModel types

TypeAdapter is capable of parsing data into any of the types Pydantic can handle as fields of a BaseModel, including BaseModel subclasses. Example: items = TypeAdapter(list[Item]).validate_python(item_data) parses a list of dictionaries into a list of Item instances.

TypeAdapter performance considerations

When creating an instance of TypeAdapter, the provided type must be analyzed and converted into a pydantic-core schema, which comes with non-trivial overhead. It is recommended to create a TypeAdapter for a given type just once and reuse it in loops or other performance-critical code.

TypeAdapter should not be used as field annotation

TypeAdapter should not be used as a type annotation for specifying fields of a BaseModel, etc., despite some overlap in use cases with RootModel.

TypeAdapter defer_build configuration

TypeAdapter supports deferred schema building through the defer_build configuration option. When set to True, Pydantic will defer building the core schema until the first time it is needed for validation or serialization. This is helpful for types with forward references or when core schema builds are expensive.

TypeAdapter.rebuild method

TypeAdapter has a rebuild method that manually triggers the building of the core schema. This is useful after forward references are defined when using defer_build=True.

TypeAdapter defer_build with forward references

Example of using TypeAdapter with defer_build=True: ta = TypeAdapter('MyInt', config=ConfigDict(defer_build=True)) defers schema building. After the forward reference is defined, call ta.rebuild() to manually trigger building, then ta.validate_python(1) works correctly.

TypeAdapter validation methods support by_alias and by_name

TypeAdapter validation methods support `by_alias` and `by_name` parameters for controlling alias usage during validation, with the same defaults and behavior as BaseModel methods.

TypeAdapter serialization methods support by_alias

TypeAdapter serialization methods support a `by_alias` parameter for controlling alias usage during serialization, with the same default behavior as BaseModel methods.

TypeAdapter supports configuration via config argument

TypeAdapter instances support configuration by providing the config argument with a ConfigDict instance. Example: ta = TypeAdapter(list[str], config=ConfigDict(coerce_numbers_to_str=True))

TypeAdapter config usage error when wrapping configurable types

Configuration cannot be provided to a TypeAdapter if the type adapter directly wraps a type that supports configuration; a usage error is raised in this case.

TypeAdapter.dump_json method

TypeAdapter has a dump_json method for serializing data to JSON, similar to BaseModel.model_dump_json.

TypeAdapter.validate_json method

TypeAdapter has a validate_json method for parsing JSON data, similar to BaseModel.model_validate_json.

TypeAdapter.json_schema method

TypeAdapter.json_schema returns a jsonable dict of an adapted type's JSON schema. It accepts parameters similar to BaseModel.model_json_schema: mode (either 'validation' or 'serialization', defaults to 'validation'), by_alias (boolean to use aliases as keys), ref_template (string to customize $ref format), and schema_generator (custom GenerateJsonSchema subclass).

Give your agent this brain