要暗示标准__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)
Run Code Online (Sandbox Code Playgroud)
要键入提示任何支持的类型,请定义具有所需行为的__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)
Run Code Online (Sandbox Code Playgroud)
请注意,序列和映射类型是通用的,并且协议也可以定义为通用的。
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1125 次 |
| 最近记录: |