Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 38 ยท Validation and Constraints

Annotated and Reusable Constrained Types

Build reusable constrained types with typing.Annotated, use PositiveInt, conint and StringConstraints, put constraints on list items, and keep rules in one place.

Field(gt=0) is fine for one field. But what if ten models share the same idea, such as "a percentage between 0 and 100" or "a username"? Copying the same Field(...) everywhere invites inconsistencies. The answer is to define the rule once as a reusable type using typing.Annotated, and then use that type everywhere.

Annotated in one minute

Annotated[Type, extra1, extra2] is standard Python: it attaches extra information to a type without changing the type itself. Type checkers see plain int; Pydantic reads the extras as validation rules.

Python Your first Annotated type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Percent is now a named concept. If the rules change (say, scores may go up to 120) you edit one line. Nothing is a new class: Percent is just an annotated int.

Ready-made constrained types

Pydantic ships common ones, so you rarely need to write them:

Type Meaning
PositiveInt, PositiveFloat greater than 0
NegativeInt, NegativeFloat less than 0
NonNegativeInt, NonNegativeFloat 0 or greater
NonPositiveInt, NonPositiveFloat 0 or less
FiniteFloat not infinity and not NaN
StrictInt, StrictStr, StrictBool... no conversion (Strict Mode)
Python Built-in constrained types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

FiniteFloat matters more than it looks: the strings "nan" and "inf" parse as valid floats, but they break statistics, JSON output and many databases.

StringConstraints

For strings, StringConstraints bundles length, pattern and cleaning options into one annotation:

Python A reusable username type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Besides checking, StringConstraints transforms: whitespace is stripped before the length and pattern rules run, and the text is lowercased after them (so the pattern above must allow capital letters, and the stored value is still all lowercase). The same type is reused for a list of usernames, so every friend is cleaned and checked too.

Constraints on items

For list[int] you can constrain the items by annotating the item type:

Python Constraints on list items

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The error location ('answers', 1) points at the offending item. Here two layers of constraints are at work: min_length on the list itself and ge/le on every element.

conint, constr and friends (the older style)

You will see functions like conint(gt=0), constr(min_length=3) and conlist(int, min_length=1) in older code. They still work, but type checkers do not understand them well, so the Annotated style is preferred in new code. Translation is mechanical:

Older Preferred
conint(ge=0, le=100) Annotated[int, Field(ge=0, le=100)]
constr(min_length=3) Annotated[str, StringConstraints(min_length=3)]
conlist(int, min_length=1) Annotated[list[int], Field(min_length=1)]

Organizing your types

A good habit is a small module, say types.py, with the types shared across the project: Username, Percent, Slug, Money. Models then read like a description of the domain: price: Money, score: Percent. When you add custom validators later, you can attach them to these types too.

Because Annotated types are ordinary Python objects, you can combine and extend them: Percent = Annotated[Score, Field(le=100)] builds on another annotated type.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of Percent = Annotated[int, Field(ge=0, le=100)]?

    A named annotated type keeps a rule in one place. It is still an int for type checkers.
  2. 2. Why is FiniteFloat useful?

    Strings like 'nan' and 'inf' convert to float values that break many computations. FiniteFloat refuses them.
  3. 3. In StringConstraints(strip_whitespace=True, min_length=3), which happens first?

    Cleaning options such as stripping run first, so ' ab ' (length 2 after stripping) fails min_length=3.
  4. 4. How do you require every int in a list to be between 1 and 5?

    Annotate the item type itself. Constraints on the list field apply to the list, not its items.

Summary

  • Annotated[T, Field(...)] defines a reusable constrained type once; use it across models.
  • Built-ins like PositiveInt, NonNegativeInt and FiniteFloat cover common cases.
  • StringConstraints combines cleaning (strip, lower) with length and pattern checks.
  • Annotate the item type to constrain list or set elements.
  • conint, constr, conlist still work, but Annotated is the modern, type-checker-friendly style.

Next: Validation Errors in Detail