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

旧巷老猫 提交于 2019-12-21 13:10:15

问题


I am using mypy to check my Python code.

I have a class where I set dynamically some attributes and mypy keep on complaining about it:

error:"Toto" has no attribute "age"

This is my code:

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" :(

Obviously, there could be 3 ways to solve the issue

  1. Ignoring the issue with # type: ignore: toto.age = 10 # type: ignore #...
  2. Using setattr to set the age of toto: setattr(toto, "age", 10)
  3. Setting the attributes explicitly (self.age = 0 ...)

However, I am looking for a more elegant and systematic way at the class level.

Any suggestion?


回答1:


I don't follow mypy well enough to know whether this is (still, or ever was) the ideal work around, but this issue and this part of the cheatsheet indicate that something like:

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

Will allow you to do what you're doing without mypy complaining (which it does, just tested).

Any could be more restrictive, but the types will be checked on both setattr() and "traditional" obj.attr = ... calls, so heads up.



来源:https://stackoverflow.com/questions/50889677/remove-error-from-mypy-for-attributes-set-dynamically-in-a-python-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!