python - mypy可以识别自定义解包吗?

标签 python mypy

我有一个提供 __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/

相关文章:

python - 在 Pyqt 中选择选项卡时未发出信号

python - 类型提示 : when to annotate

python - 当将 boolean 值与整数混合时,Mypy不会引发错误

python - 在 python 中反转 dict 和访问它的值的正确方法是什么?

python - Linux shell : Base64 Decode with removing line breaks

Python按字段对文本文件进行排序

python - 按数组名称追加数组

python - 在不同的机器上用 mypy 扫描一个包会产生不同的结果

python - 使用条件参数进行类型检查

python - 在 Python 中修改闭包的绑定(bind)变量