Mypy:属性设置器分配中的类型不兼容

Yoh*_*hei 7 python typing mypy

我想与 mypy 一起使用property setter。属性 getter 和 setter 的类型不同:

from typing import List, Iterable

class Foo:
    @property
    def x(self) -> List[int]:
        ...

    @x.setter
    def x(self, new_x: Iterable[int]):
        ...

foo = Foo()
foo.x = (1, 2, 3) # error: Incompatible types in assignment (expression has type "Tuple[int, int, int]", variable has type "List[int]")

Run Code Online (Sandbox Code Playgroud)

我该如何处理这个错误?

小智 1

Mypy 抱怨类型不兼容,因为 Tuple 具有不同的签名:

# For tuples, we specify the types of all the elements
x: Tuple[int, str, float] = (3, "yes", 7.5)
Run Code Online (Sandbox Code Playgroud)

对于 setter 和 getter,如果您只是将 setter 的输入参数分配给类变量,则类型应该相同。Iterable[int] 和 Tuple[int,int,int] 是不同的类型,因为在这种情况下 tuple 是不可变对象并且有 3 个元素.

处理此错误的方法是在设置为 foo.x 之前将元组转换为列表:

foo.x = list((1,2,3))
Run Code Online (Sandbox Code Playgroud)

  • 我不希望用户这样做。我将 setter 定义为具有与 getter 不同的类型签名,因为 setter 实际上可以接受所有 Iterable,并在内部对其进行转换。 (7认同)