我想类型检查函数的参数是否可以下标。如何使用Python的typing
模块执行此操作?
我已经搜索了文档,但没有找到任何东西。但是也许可以创建一个自定义Type
。我该怎么办?
暗示标准的__getitem__
行为,使用的通用版本collections.abc
,如typing.Sequence
,typing.MutableSequence
,typing.Mapping
,或typing.MutableMapping
。
from typing import Mapping
def get(container: Mapping, key):
return container[key]
get({1: 'one', 2: 'two'}, 2)
要键入hint支持的任何类型,请__getitem__
定义typing.Protocol
具有所需行为的自定义。
from typing import Protocol, Any
class Lookup(Protocol):
def __getitem__(self, key) -> Any: ...
def get(container: Lookup, key):
return container[key]
get(['zero', 'one', 'two'], 2)
注意,序列和映射类型是通用的,协议也可以定义为通用的。
from typing import Protocol, TypeVar
K = TypeVar('K', contravariant=True)
V = TypeVar('V', covariant=True)
class Lookup(Protocol[K, V]):
def __getitem__(self, key: K) -> V: ...
def get(container: Lookup[K, V], key: K) -> V:
return container[key]
get({1: 'one', 2: 'two'}, 2) # succeeds type checking
get({1: 'one', 2: 'two'}, '2') # fails type checking
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句