← 中文资源

简体中文版本

Annotated 携带运行时元数据

Annotated 把校验边界直接挂在字段类型旁:Within 标记携带上下限,get_type_hints 加 include_extras=True 才能取回元数据,运行时校验据此逐字段检查。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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

实现说明

逻辑集中在类 from、Within、class和函数 __init__、validate里。 本示例的循环部分是 for field, hint in hints.items()。

使用要点

  • 值得导入的表面是 validate;周围的辅助代码对片段是私有的。

常见问题

这段代码会引入外部包吗?

不涉及外部包,每个调用都落在内建 API 上。 文件在加载时定义 __init__、validate。

入口签名:def validate(instance) -> list[str]

核心语句

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

代码示例

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)))