Annotated Carries Runtime Metadata

Annotated attaches validation markers next to field types, and get_type_hints with include_extras recovers them for runtime checks.

PythonForm Validation

Code

pythonsnippet
32 lines
from dataclasses import dataclass
from typing import Annotated, get_type_hints


class Within:
    """自定义校验标记:把合法边界挂在字段类型旁边。"""

    def __init__(self, low: int, high: int) -> None:
        self.low, self.high = low, high


@dataclass
class Profile:
    name: str
    age: Annotated[int, Within(0, 130)]
    retries: Annotated[int, Within(0, 5)] = 3


def validate(instance) -> list[str]:
    # include_extras=True 才能在 hint 上拿到 Annotated 元数据
    hints = get_type_hints(type(instance), include_extras=True)
    problems = []
    for field, hint in hints.items():
        value = getattr(instance, field)
        for marker in getattr(hint, '__metadata__', ()):
            if isinstance(marker, Within) and not marker.low <= value <= marker.high:
                problems.append(f'{field}={value} outside [{marker.low}, {marker.high}]')
    return problems


print(validate(Profile(name='ada', age=30, retries=2)))
print(validate(Profile(name='bo', age=999, retries=9)))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

[]
['age=999 outside [0, 130]', 'retries=9 outside [0, 5]']

Annotated Carries Runtime Metadata: the mechanics

One way to read it: the classes from, Within and class and the functions __init__ and validate, doing all the work.

A single loop drives the file — for field, hint in hints.items().

What to watch for

  • Every call is a built-in — there is no supply chain to review.

Using it

The one signature in play: def validate(instance) -> list[str]

Callers only need validate — everything else stays internal.

Key statements

def __init__(self, low: int, high: int) -> None:
    self.low, self.high = low, high

Interactive Tools for This Topic

FAQ

Does the code pull in any external packages?
No external packages are involved; every call resolves to a built-in API. The file defines `__init__`, `validate` at load time.