annotated-types

0.7.0 · active · verified Sat Mar 28

annotated-types provides reusable constraint metadata objects—such as Gt, Lt, Len, MultipleOf, Timezone, Predicate, and more—to be used with typing.Annotated (PEP 593). It does not enforce constraints itself; enforcement is left to consuming libraries like Pydantic, Hypothesis, or custom validators. Current version is 0.7.0 (released 2024). The project follows an irregular, feature-driven release cadence and was created at PyCon 2022 by the Pydantic and Hypothesis maintainers.

Warnings

Install

Imports

Quickstart

Demonstrates scalar bounds, collection length constraints, predicates, IsDigits, and Timezone usage, plus how to introspect annotations from Annotated types. No auth required.

from typing import Annotated, get_args, get_origin
import math
from annotated_types import Gt, Lt, Len, MinLen, MaxLen, MultipleOf, Predicate, Interval, Timezone, IsDigits
from datetime import datetime, timezone

# Scalar bounds
PositiveInt = Annotated[int, Gt(0)]
SmallFloat = Annotated[float, Interval(ge=0.0, le=1.0)]

# Collection length (both bounds inclusive since v0.4.0)
ShortList = Annotated[list, Len(1, 10)]
NonEmptyStr = Annotated[str, MinLen(1)]
CappedStr = Annotated[str, MaxLen(255)]

# Predicate — prefer introspectable callables over lambdas
FiniteFloat = Annotated[float, Predicate(math.isfinite)]
DigitOnly = Annotated[str, IsDigits]

# Timezone (v0.7.0+: accepts tzinfo objects)
UTCDatetime = Annotated[datetime, Timezone(timezone.utc)]
AwareDatetime = Annotated[datetime, Timezone(...)]
NaiveDatetime = Annotated[datetime, Timezone(None)]

# Reading metadata back (for library authors)
def show_constraints(tp):
    if get_origin(tp) is Annotated:
        base, *metadata = get_args(tp)
        print(f"Base type: {base}, constraints: {metadata}")

show_constraints(Annotated[int, Gt(0), Lt(100)])

view raw JSON →