实现说明
逻辑集中在类 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)))