How can I make mypy remember hasattr?

Viewed 647

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"
1 Answers

This isn't the answer being sought, but putting it here as one approach. Look forward to seeing other answers.

Fwiw, defining a variable annotation won't result in a new table column, but even if it was a class level variable that wasn't an instance of a model field, Django would know better.

from typing import Any

class MakeNoiseMixin:
    cat: Any
    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!")


felix = Cat()
felix.make_noise()
$ mypy example.py --check-untyped-defs
Success: no issues found in 1 source file
Related