Skip to content

Commit

Permalink
Docs updates: type adapter rebuild instructions (pydantic#10849)
Browse files Browse the repository at this point in the history
  • Loading branch information
sydney-runkle authored Nov 15, 2024
1 parent c36a0b9 commit 11d04f3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
31 changes: 30 additions & 1 deletion docs/concepts/type_adapter.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,35 @@ print(items)
handle as fields of a [`BaseModel`][pydantic.main.BaseModel].

!!! info "Performance considerations"
When creating an instance of `TypeAdapter`, the provided type must be analyzed and converted into a pydantic-core
When creating an instance of [`TypeAdapter`][pydantic.type_adapter.TypeAdapter], the provided type must be analyzed and converted into a pydantic-core
schema. This comes with some non-trivial overhead, so it is recommended to create a `TypeAdapter` for a given type
just once and reuse it in loops or other performance-critical code.


### Rebuilding a `TypeAdapter`'s schema

In v2.10+, [`TypeAdapter`][pydantic.type_adapter.TypeAdapter]'s support deferred schema building and manual rebuilds. This is helpful for the case of:
* Types with forward references
* Types for which core schema builds are expensive

When you initialize a [`TypeAdapter`][pydantic.type_adapter.TypeAdapter] with a type, Pydantic analyzes the type and creates a core schema for it.
This core schema contains the information needed to validate and serialize data for that type.
See the [architecture documentation](../internals/architecture.md) for more information on core schemas.

If you set [`defer_build`][pydantic.config.ConfigDict.defer_build] to `True` when initializing a `TypeAdapter`,
Pydantic will defer building the core schema until the first time it is needed (for validation or serialization).

In order to manually trigger the building of the core schema, you can call the
[`rebuild`][pydantic.type_adapter.TypeAdapter.rebuild] method on the [`TypeAdapter`][pydantic.type_adapter.TypeAdapter] instance:

```py
from pydantic import ConfigDict, TypeAdapter

ta = TypeAdapter('MyInt', config=ConfigDict(defer_build=True))

# some time later, the forward reference is defined
MyInt = int

ta.rebuild()
assert ta.validate_python(1) == 1
```
2 changes: 2 additions & 0 deletions pydantic/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,8 @@ class Model(BaseModel):
This can be useful to avoid the overhead of building models which are only
used nested within other models, or when you want to manually define type namespace via
[`Model.model_rebuild(_types_namespace=...)`][pydantic.BaseModel.model_rebuild].
Since v2.10, this setting also applies to pydantic dataclasses and TypeAdapter instances.
"""

plugin_settings: dict[str, object] | None
Expand Down

0 comments on commit 11d04f3

Please sign in to comment.