I am checking with hasattr
if an object has an attribute. If it exists, I assign it. However, mypy still complains has no attribute
. How can I help mypy to remember that this attribute exists?
MVCE
Save as example.py
:
from typing import Any
class MakeNoiseMixin:
def make_noise(self):
if isinstance(self, Cat) or hasattr(self, "cat"):
cat = self if isinstance(self, Cat) else self.cat
cat.meow()
else:
print("zZ")
class Cat(MakeNoiseMixin):
def meow(self):
print("meow!")
class Dog(MakeNoiseMixin):
...
class Human(MakeNoiseMixin):
def __init__(self, cat):
self.cat = cat
felix = Cat()
felix.make_noise()
tom = Dog()
tom.make_noise()
felix_owner = Human(felix)
felix_owner.make_noise()
Run:
$ python example.py
meow!
zZ
meow!
$ example.py --check-untyped-defs
example.py:4: error: "MakeNoiseMixin" has no attribute "cat"