正如 AntiNeutronicPlasma 所说,Maxlen 只是一个示例,因此您需要自己创建它。
这是一个示例,说明如何创建和解析自定义注释,例如 MaxLen 以帮助您入门。
首先,我们定义注解类本身。这是一个很简单的类,我们只需要存储相关的元数据,这里就是最大值:
class MaxLen:
def __init__(self, value):
self.value = value
现在,我们可以定义一个使用这个注解的函数,例如:
def sum_nums(nums: Annotated[List[int], MaxLen(10)]):
return sum(nums)
但如果没有人检查它,它就没什么用了。因此,一种选择可能是实现一个在运行时检查您的自定义注释的装饰器。 typing 模块中的函数get_type_hints、get_origin 和get_args 将成为你最好的朋友。下面是这样一个装饰器的示例,它解析并强制 list 类型上的 MaxLen 注释:
from functools import wraps
from typing import get_type_hints, get_origin, get_args, Annotated
def check_annotations(func):
@wraps(func)
def wrapped(**kwargs):
# perform runtime annotation checking
# first, get type hints from function
type_hints = get_type_hints(func, include_extras=True)
for param, hint in type_hints.items():
# only process annotated types
if get_origin(hint) is not Annotated:
continue
# get base type and additional arguments
hint_type, *hint_args = get_args(hint)
# if a list type is detected, process the args
if hint_type is list or get_origin(hint_type) is list:
for arg in hint_args:
# if MaxLen arg is detected, process it
if isinstance(arg, MaxLen):
max_len = arg.value
actual_len = len(kwargs[param])
if actual_len > max_len:
raise ValueError(f"Parameter '{param}' cannot have a length "
f"larger than {max_len} (got length {actual_len}).")
# execute function once all checks passed
return func(**kwargs)
return wrapped
(请注意,此特定示例仅适用于关键字参数,但您可能会找到一种方法使其也适用于普通参数)。
现在,您可以将此装饰器应用于任何函数,您的自定义注释将被解析:
from typing import Annotated, List
@check_annotations
def sum_nums_strict(nums: Annotated[List[int], MaxLen(10)]):
return sum(nums)
以下是实际代码示例:
>>> sum_nums(nums=list(range(5)))
10
>>> sum_nums(nums=list(range(15)))
105
>>> sum_nums_strict(nums=list(range(5)))
10
>>> sum_nums_strict(nums=list(range(15)))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "annotated_test.py", line 29, in wrapped
raise ValueError(f"Parameter '{param}' cannot have a length "
ValueError: Parameter 'nums' cannot have a length larger than 10 (got length 15).