[英]Subscriptable Type in Python typing
我想键入检查函数的参数是否可下标。 我如何使用 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)
要键入支持__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
沿着这些路线的东西(虽然完全未经测试)应该这样做:
from typing import Protocol, TypeVar
K = TypeVar("K")
V = TypeVar("V")
class Subscriptable(Protocol[K, V]):
def __getitem__(self, k: K) -> V:
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.