Skip to content
Sarj Code Standards

no-per-call-type-adapter

Build a pydantic TypeAdapter once instead of on every call.

Why

Each TypeAdapter construction rebuilds the pydantic-core validator and serializer for its type, so building one inside a function repeats that work on every call.

Fix

Hoist the adapter to a module constant, or build it in a functools.cache factory keyed by the type when the type is only known at run time.

Examples

Before — flagged Do not build an adapter on every call
app/parse.py
from pydantic import TypeAdapter
def parse(raw):
return TypeAdapter(list[int]).validate_json(raw)
After — preferred Reuse a module-level adapter
app/parse.py
from pydantic import TypeAdapter
INTS = TypeAdapter(list[int])
def parse(raw):
return INTS.validate_json(raw)