Pydantic Validation
In a nutshell, Pydantic is dataclasses with runtime validation. It leverages type hints to understand how validation (and serialization) should be performed. It is mostly useful when dealing with external untrusted data, for example when defining an HTTP API.
It is generally not recommended to use Pydantic to define classes that are instantiated within the user code. By doing so, you will lose flexibility (e.g. you cannot use types not supported by Pydantic, and it is harder to perform post-init changes). It is usually better to use vanilla classes (or standard library dataclasses) in this case, as a static type checker will already catch type mismatches.
Basic usage
Here is a simple example of using a Pydantic model:
Pydantic coerces compatible input: the ISO date string '1970-01-01' is parsed into a date.
Constraints and field metadata
The Field() function is used to provide metadata and constraints.
You need to distinguish two types of metadata:
- field specific metadata: metadata such as
deprecatedandalias, that only have meaning when attached to a field. - type specific metadata: this includes constraints such as
gt,max_length, and also metadata that affects the JSON Schema (e.g.description,title).
Model fields are declared with Field() using the assignment form:
or using the annotated pattern:
The annotated pattern has some advantages:
- Using the
f: <type> = Field()form (no default) can be confusing and might trick users into thinkingfhas a default value, while in reality the field is still required. - You can provide an arbitrary amount of metadata elements for a field. As shown in the example above,
the
Field()function only supports a limited set of constraints/metadata, and you may have to use different Pydantic utilities such asWithJsonSchemain some cases.
But note that:
-
You should use the assignment form for metadata that has a meaning for static type checkers. This includes:
alias,defaultanddefault_factory. -
field specific metadata can only be used on the "top-level" type. A common pitfall is to do the following:
field specific metadata should apply to the whole union in this example.
Constraints
As much as possible, use the "built-in" validation constraints, instead of defining custom validators:
Sometimes, constraints can't be expressed using the Field() function. For example, string constraints such
as strip_whitespace, to_upper, to_lower and ascii_only can only be specified using pydantic.StringConstraints:
https://pydantic.dev/docs/validation/latest/api/pydantic/standard_library_types/ is the canonical documentation for all supported standard library types and their constraints.
Validators
In some cases, you may have to use custom validators. As much as possible, use after validators. Because they run after Pydantic validation, the value is already the field's type. If you use before validators, the input data can literally be anything, so it is more error-prone (especially for model validators, the input isn't necessarily a dict, it can also be an arbitrary object).
If possible, prefer using the annotated pattern for validators:
Using the decorator pattern can lead to unclear behavior, especially regarding the order in which validators run (in particular on subclasses).
Type coercion, collections and unions
Unless you are using strict mode, Pydantic applies
type coercion in most cases. For instance, for a field typed as int, strings like '123' will be accepted. This also
applies to collection types: list[str] also accepts tuples, sets etc.
This is why you should avoid:
- using unions such as
int | str, if your goal is to coerce thestrto anintvia a validator. - using abstract collections such as
collections.abc.Sequence, if your goal is to accept both lists and tuples. Using these abstract collections is inefficient.
In the general case, unions are best avoided because every use of the field will need to check for each type before doing anything with it.
Forward annotations
Python has the ability to write annotations as forward references, by using strings. This can cause challenges for Pydantic to evaluate them, so they are best avoided if possible.
If you are defining Pydantic models in a module, avoid using from __future__ import annotations if possible
(which stringifies all annotations by default). Only add explicit quotes to annotations that aren't defined yet, e.g.:
Also note that in Python >= 3.14, annotation evaluation is deferred, so you should not use string annotations at all.
Recursive type aliases
You might be tempted to define aliases like this:
The alias needs to be quoted because it is recursive. Pydantic will generally not be able to evaluate a quoted TypeAlias.
Instead, use an explicit type alias (type on Python 3.12+, or TypeAliasType), which Pydantic can resolve:
Model subclasses, discriminated unions
Subclassing is a really common Python pattern, but can be a footgun in Pydantic. You might be tempted to do:
This example works, but will not behave as expected when serializing m:
This is because Pydantic serializes according to the declared type (Base), not the runtime subclass.
Validation follows the same rule: Main(model={'base_field': 1, 'sub1_field': 'test'}) validates against Base,
so sub1_field is ignored rather than producing a Sub1 instance.
Instead, try to use discriminated unions (provided that you can set a type field to distinguish models):
or generics:
If neither discriminated unions nor generics fit, polymorphic serialization (in Pydantic >=2.13) or serialize as any (in Pydantic <2.13) can be used as a last resort.


