我知道有一种新的类型格式,Annotated您可以在其中为函数的入口变量指定一些元数据。从文档中,您可以指定传入列表的最大长度,例如:
- Annotated 可以与嵌套和通用别名一起使用:
T = TypeVar('T')
Vec = Annotated[list[tuple[T, T]], MaxLen(10)]
V = Vec[int]
V == Annotated[list[tuple[int, int]], MaxLen(10)]
Run Code Online (Sandbox Code Playgroud)
但我无法完全理解到底是什么MaxLen。你应该从其他地方导入一个类吗?我尝试过导入typing.MaxLen,但似乎不存在(我正在使用Python 3.9.6,我认为它应该存在于此处...?)。
我想象它应该有效的示例代码:
from typing import List, Annotated, MaxLen
def function(foo: Annotated[List[int], MaxLen(10)]):
# ...
return True
Run Code Online (Sandbox Code Playgroud)
哪里可以找到MaxLen?
编辑:
看起来MaxLen你必须创建某种类。问题是我不知道你应该怎么做。有公开的例子吗?有人如何实现这个功能?