Annotated Carries Runtime Metadata
Annotated attaches validation markers next to field types, and get_type_hints with include_extras recovers them for runtime checks.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.