python - 如何让 mypy 记住 hasattr?
问题描述
我正在检查hasattr
对象是否具有属性。如果它存在,我分配它。但是,mypy 仍然抱怨has no attribute
。我如何帮助 mypy 记住该属性存在?
MVCE
另存为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()
跑:
$ python example.py
meow!
zZ
meow!
$ example.py --check-untyped-defs
example.py:4: error: "MakeNoiseMixin" has no attribute "cat"
解决方案
这不是正在寻求的答案,而是将其作为一种方法放在这里。期待看到其他答案。
Fwiw,定义变量注释不会导致新的表列,但即使它是一个不是模型字段实例的类级别变量,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
推荐阅读
- python - 使用 pdfminer python 从 PDF 文件中提取信息
- php - “错误”:“array_merge():预期参数 1 是一个数组,给定 null”
- caching - CPU 中的抗锯齿硬件是否保守地使条目无效?
- ember.js - Emberjs - 在组件中使用 @model 钩子数据
- javascript - 无法在正则表达式中找到正向前瞻 (?=pattern) 示例的匹配项
- c++ - C++ lower_bound() 搜索最接近目标值的元素
- stata - 为什么我在 Stata 中的虚拟变量转换会产生:类型不匹配?
- ios - 如何更改 UITableView 中的部分标题文本颜色
- c++ - 如何以“安全”的方式在 C++ 中获取当前时间
- python-3.6 - 我如何打印只有 a_list 中的第一个和最后一个数字以及每个数字之间的“to”的范围?