Python 输入中的可订阅类型
Subscriptable Type in Python typing
我想对函数的参数进行类型检查以确保它是可订阅的。如何使用 Python 的 typing
模块执行此操作?
我搜索了文档,但没有找到任何内容。但也许可以创建自定义 Type
。我该怎么做?
要暗示标准 __getitem__
行为,请使用 collections.abc
的通用版本,例如 typing.Sequence
, typing.MutableSequence
, typing.Mapping
, or 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:
...
我想对函数的参数进行类型检查以确保它是可订阅的。如何使用 Python 的 typing
模块执行此操作?
我搜索了文档,但没有找到任何内容。但也许可以创建自定义 Type
。我该怎么做?
要暗示标准 __getitem__
行为,请使用 collections.abc
的通用版本,例如 typing.Sequence
, typing.MutableSequence
, typing.Mapping
, or 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:
...