Mypy对attrs装饰类的子类报错Unexpected keyword argument如何解决?
该报错本质是Mypy默认未开启attrs的完整类型支持,无法识别@attr.s装饰器为子类生成的、继承自父类的构造函数字段,而attrs运行时逻辑本身会正确把父类字段加入子类构造参数,所以代码执行无异常但静态检查报错。
以下是可行的解决方法:
- 方法1:开启Mypy的attrs插件支持(推荐,无需修改现有代码)
在项目的Mypy配置文件(mypy.ini/pyproject.toml/.mypyrc)中添加attrs插件配置:
如果是pyproject.toml配置:
[tool.mypy] plugins = ["attrs.mypy"]
如果是mypy.ini配置:
[mypy] plugins = attrs.mypy
配置完成后重新执行Mypy检查即可消除报错。
- 方法2:升级为attrs新版本官方推荐写法
如果使用的attrs版本≥20.1.0,可以把旧的@attr.s+attr.ib写法替换为更符合PEP规范的@define装饰器写法,Mypy对这种写法的默认支持度更高,无需额外配置即可识别继承参数:
from attrs import define @define(kw_only=True) class Entity: """ base class of all entities """ entity_id: str # ... @define(kw_only=True) class Customer(Entity): customer_name: Name # ...
- 临时规避方法
如果暂时不想修改配置或代码,可以在报错的构造语句行末尾添加# type: ignore注释跳过本次检查,但该方法不推荐长期使用:
def register_customer(customer_name: str): return Customer( entity_id=unique_id_generator(), customer_name=Name(full_name=customer_name), ) # type: ignore
内容的提问来源于stack exchange,提问作者omid
相关产品推荐
相关产品推荐

