我有一个提供 __getitem__
的类 - python 很乐意使用它来解包,但是当我在代码上运行 mypy 时,我得到 List 或 tuple 预期作为变量参数
.
这是一个最小的再现器
from typing import Any
class Foo:
def __getitem__(self, idx: int) -> Any:
if idx == 0:
return 1
if idx == 1:
return "bye"
else:
raise IndexError
f = Foo()
t = ("hello", *f)
print(t) # prints ("hello", 1, "bye")
我不想在我执行的每个点上添加错误抑制*f
,这违背了类的全部目的。
有什么方法可以让 mypy 明白解压 Foo
是可以的吗?
如果重要的话,我目前正在使用 mypy 0.800 和 Python 3.7.6。
最佳答案
看起来 MyPy 期望可解压对象具有 __iter__
方法——在某种程度上,这很公平,因为对象实现 __getitem__
的情况相当罕见。并没有实现__iter__
。你可以通过一点点谎言来消除 MyPy 错误:告诉 MyPy 有一个 __iter__
方法,即使您无意实现一种方法。似乎适用于 python 3.7/MyPy 0.800 以及 python 3.10/MyPy 0.910。
from typing import Any, Callable, Iterator
class Foo:
__iter__: Callable[["Foo"], Iterator[Any]]
def __getitem__(self, idx: int) -> Any:
if idx == 0:
return 1
if idx == 1:
return "bye"
else:
raise IndexError
f = Foo()
t = ("hello", *f)
print(t) # prints ("hello", 1, "bye")
关于python - mypy可以识别自定义解包吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68675692/