从 mypy 中删除 Python class 中动态设置的属性的错误

Remove error from mypy for attributes set dynamically in a Python class

我正在使用 mypy 检查我的 Python 代码。

我有一个 class 我动态设置了一些属性并且 mypy 一直抱怨它:

error:"Toto" has no attribute "age"

这是我的代码:

class Toto:
    def __init__(self, name:str) -> None:
        self.name = name
        for attr in ['age', 'height']:
            setattr(self, attr, 0)


toto = Toto("Toto")
toto.age = 10  # "Toto" has no attribute "age" :(

显然,有 3 种方法可以解决这个问题

  1. 忽略 # type: ignore 的问题:toto.age = 10 # type: ignore #...
  2. 使用setattr设置totoagesetattr(toto, "age", 10)
  3. 显式设置属性(self.age = 0 ...)

不过,我正在寻找class级别更优雅、更系统的方法。

有什么建议吗?

我对 mypy 的了解不够好,不知道这是否(仍然是,或者曾经是)理想的解决方法,但是 this issue and this part of the cheatsheet 指出类似的东西:

from typing import Any

class Toto:
    def __init__(self, name:str) -> None:
        self.name = name
        for attr in ['age', 'height']:
            setattr(self, attr, 0)

    def __setattr__(self, name:str, value:Any):
        super().__setattr__(name, value)

toto = Toto("Toto")
toto.age = 10

将允许你在没有 mypy 抱怨的情况下做你正在做的事情(它确实如此,刚刚测试过)。

Any 可能会更严格,但会在 setattr() 和 "traditional" obj.attr = ... 调用时检查类型,所以请注意。