简体   繁体   English

如何让 mypy 记住 hasattr?

[英]How can I make mypy remember hasattr?

I am checking with hasattr if an object has an attribute.如果 object 具有属性,我正在检查hasattr If it exists, I assign it.如果它存在,我分配它。 However, mypy still complains has no attribute .但是,mypy 仍然抱怨has no attribute How can I help mypy to remember that this attribute exists?我如何帮助 mypy 记住该属性存在?

MVCE MVCE

Save as example.py :另存为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"

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. Fwiw,定义一个变量注释不会产生一个新的表列,但即使它是一个 class 级别的变量不是 model 字段的实例,Django 会更好地知道。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM