Pydantic: Reusable Validation with Annotated Types

Pydantic's `Annotated` attaches validation logic directly to a type, making it reusable. Define a custom type like `SquareNumber` once and apply it to any model field, ensuring consistent validation without repeating code.
Pydantic's `Annotated` attaches validation logic directly to a type, making it reusable across models. Instead of decorating a specific field, you bundle validators with the type itself, creating custom types like `PositiveInt` or `NonEmptyString`. Define it once, then apply it to any model field to enforce consistent rules without repeating code. The main footgun is using `BeforeValidator`s; they run on raw input before Pydantic's type coercion, so you must handle unexpected data types yourself, unlike safer `AfterValidator`s.
Read the original → pydantic.dev
- #pydantic
- #python
- #validation
- #typing
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.