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

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página