Python 中的可下标类型

jon*_*ach 5 python typing

我想检查函数的参数是否可下标。我如何使用Python的typing模块来做到这一点?

我搜索了文档但没有找到任何东西。但也许可以创建自定义Type. 我该怎么做呢?

Mis*_*agi 4

要暗示标准__getitem__行为,请使用 的通用版本collections.abc,例如typing.Sequencetyping.MutableSequencetyping.Mappingtyping.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)