支持 __getitem__ 的类的 Python 类型提示 [英] Python type hint for classes that support __getitem__
问题描述
我想向一个函数添加类型提示,该函数将接受带有 __getitem__
方法的任何对象.例如,在
I want to add type hints to a function that will accept any object with a __getitem__
method. For instance, in
def my_function(hasitems, locator):
hasitems[locator]
我不想将 hasitems
限制为像 list
或 dict
这样的特定类型.只要它支持 __getitem__
,它就是 my_function
的合适参数.如何在没有不必要限制的情况下注释其类型?
I don't want to restrict hasitems
to be a specific type like list
or dict
. As long as it supports __getitem__
, it's an appropriate argument to my_function
. How can I annotate its type without being unnecessarily restrictive?
显然 PyCharm 可以在许多常见情况下推断出适当的提示,但在我的实际用例中却不能.我无法发布代码,因为它用于工作,而且我无法找到 PyCharm 失败的非专有最小示例.在任何情况下,原始问题都没有引用 PyCharm,它仍然是类型提示的有效用例.
apparently PyCharm can deduce the appropriate hint in a number of common cases, but not in my actual use case. I can't post the code since it's for work, and I haven't been able to find a nonproprietary minimal example where PyCharm fails. In any case, the original question doesn't reference PyCharm and it is still a valid use case for type hints.
推荐答案
如果您愿意为 typing
安装一个不太正式的扩展,typing-extensions,你可以使用Protocol
,它应该是PEP-0544:
If you're willing to install a not-quite-offical extension to typing
, typing-extensions, you can use a Protocol
, which should be an implementation of 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
这篇关于支持 __getitem__ 的类的 Python 类型提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!