实现说明
整个示例围绕函数 matches_list组织。
for name, hint in hints.items() 是唯一的迭代点——其余代码顺序执行一遍。
使用要点
- 跑完文件,输出里会留下标记——
union:。 - 把
matches_list当作 API:导入它,其余代码可以忽略。
常见问题
需要标准库之外的东西吗?
除标准库外不引入任何东西——这个示例没有依赖。 文件在加载时定义 matches_list。
主要签名是 def matches_list(value, hint) -> bool
核心语句
def matches_list(value, hint) -> bool:
if get_origin(hint) is not list or not isinstance(value, list):
return False
return all(isinstance(item, get_args(hint)[0]) for item in value)
代码示例
from typing import get_args, get_origin
hints = {
'ids': list[int],
'scores': dict[str, float],
'label': str | None,
'payload': tuple[str, int],
'blob': bytes,
}
# 泛型别名拆成 (origin, args);普通类型 origin 为 None、args 为空
for name, hint in hints.items():
print(f'{name:>8}:', get_origin(hint), get_args(hint))
# Union 拆出全部成员,NoneType 就是"可空"
print('union:', get_origin(str | None), get_args(str | None))
# 运行时校验单参数容器:容器类型与元素类型都对上才算通过
def matches_list(value, hint) -> bool:
if get_origin(hint) is not list or not isinstance(value, list):
return False
return all(isinstance(item, get_args(hint)[0]) for item in value)
print(matches_list([1, 2, 3], list[int]))
print(matches_list([1, 'x'], list[int]))
print(matches_list((1, 2), list[int]))