Mypy无法识别单例类属性,抛出[attr-defined]和[no-untyped-def]错误
解决Python单例类的Mypy校验错误
原代码
class WaitService: _instance = None def __new__(cls, name: str = "Default"): if not cls._instance: cls._instance = super(WaitService, cls).__new__(cls) cls._instance.name = name return cls._instance if __name__ == '__main__': w = WaitService("at till 9pm") print(w.name)
Mypy校验错误
error: "WaitService" has no attribute "name" [attr-defined]
error: Function is missing a return type annotation [no-untyped-def]
错误解决方法
1. 修复"has no attribute 'name'"错误
Mypy无法识别动态添加的name属性,需要在类中显式声明该属性的类型,让类型检查器知晓其存在:
- 在类内部添加
name: str的类型注解。
2. 修复"missing a return type annotation"错误
__new__方法需要明确标注返回类型,由于是单例模式,返回的是当前类的实例,直接标注返回类型为WaitService(Python 3.10+可使用更简洁的Self类型)。
修正后的代码(兼容Python 3.8+)
from typing import Optional class WaitService: _instance: Optional['WaitService'] = None name: str # 显式声明name属性类型 def __new__(cls, name: str = "Default") -> 'WaitService': if not cls._instance: cls._instance = super().__new__(cls) cls._instance.name = name return cls._instance if __name__ == '__main__': w = WaitService("at till 9pm") print(w.name)
更简洁的Python 3.10+版本
使用typing.Self类型替代字符串前向引用,代码可读性更好:
from typing import Optional, Self class WaitService: _instance: Optional[Self] = None name: str def __new__(cls, name: str = "Default") -> Self: if not cls._instance: cls._instance = super().__new__(cls) cls._instance.name = name return cls._instance if __name__ == '__main__': w = WaitService("at till 9pm") print(w.name)
内容的提问来源于stack exchange,提问作者Uchenna Nwanyanwu
相关产品推荐
相关产品推荐

