Skip to content

PY-TYPE0007 · repeated_annotated_constraint

Find repeated inline constrained annotations that deserve a named type alias.

This is a deterministic rule for python. Read its implementation.

Canonicalize inline Annotated field, parameter, and return annotations containing Pydantic, functional-validator, or annotated-types constraints. Group identical recipes across the project. Report a recipe after it reaches both minimum_repetitions and minimum_files, unless it already lives in a configured shared typing module. Metadata that is field-specific, including defaults, aliases, titles, descriptions, and discriminators, is excluded because Pydantic does not permit it inside a named type alias.

Each finding shows the exact annotation recipe, occurrence count, affected file count, nearest shared typings.py destination, and every matching source location. The result value counts all reusable inline constrained annotations, including unique recipes.

A local recipe stays inline until repetition proves a shared concept. Keep aliases near one bounded context when a project-wide alias would couple unrelated domains. Configure another filename when the project deliberately owns typing aliases elsewhere. preferred_modules names the layouts that already are a shared location, so a destination ending in one of them is stable rather than reported again.

Bad

Repeating `Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)]` in three
fields across two modules produces one finding.
Good

Define type NonEmptyText = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] once in the nearest shared typings.py, then annotate those fields with NonEmptyText. One isolated constrained field remains inline.

  • Cites “Pydantic documentation”, validators, reusable annotated pattern. Open reference
  • Cites “Pydantic documentation”, custom types, named PEP 695 aliases. Open reference
  • Cites “Python typing specification”, type aliases. Open reference