[英]Python type hint for classes that support __getitem__
我想将类型提示添加到一个函数,该函数将接受具有__getitem__
方法的任何对象。 例如,在
def my_function(hasitems, locator):
hasitems[locator]
我不想将hasitems
限制为像list
或dict
这样的特定类型。 只要它支持__getitem__
,它就是my_function
的合适参数。 如何在不受不必要限制的情况下对其类型进行注释?
编辑:显然PyCharm可以在许多常见案例中推断出适当的提示,但不是在我的实际用例中。 我不能发布代码,因为它是为了工作,我无法找到PyCharm失败的非专有的最小例子。 在任何情况下,原始问题都没有引用PyCharm,它仍然是类型提示的有效用例。
这适用于dict和list,但不适用于任何泛型类型:
from typing import Any, Mapping, Sequence, Union
def my_function(hasitems: Union[Mapping, Sequence], locator: Any) -> Any:
return hasitems[locator]
如果您愿意安装一个非常官方的扩展名来typing
, 输入扩展名 ,您可以使用一个Protocol
,它应该是PEP-0544的一个实现:
from typing_extensions import Protocol
from typing import Any
class GetItem(Protocol):
def __getitem__(self: 'Getitem', key: Any) -> Any: pass
class BadGetItem:
def __getitem__(self, a: int, b: int) -> Any: pass
def do_thing(arg: GetItem):
pass
do_thing(dict()) # OK
do_thing(BadGetItem()) # Fails with explanation of correct signature
do_thing(1) # Fails
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.