我想类型检查函数的参数是否可以下标。如何使用Python的typing
模块执行此操作?
我已经搜索了文档,但是没有找到任何东西。但是也许可以创建自定义Type
。我该怎么办?
遵循这些原则(尽管完全未经测试):
from typing import Protocol, TypeVar
K = TypeVar("K")
V = TypeVar("V")
class Subscriptable(Protocol[K, V]):
def __getitem__(self, k: K) -> V:
...
要提示标准的__getitem__
行为,请使用collections.abc
的通用版本,例如typing.Sequence
,typing.MutableSequence
,typing.Mapping
或typing.MutableMapping
。