简体   繁体   English

如何使用python-attrs构造解决“意外的关键字参数”,让mypy开心?

[英]How to solve "unexpected keyword argument" with python-attrs construct, so that mypy is happy?

I have a class A in a foreign library.我在外国图书馆有一个class A

class A:
    def __init__(self, a: int):
        self.a = a

I would like to extend a class B with A like:我想用A扩展class B ,例如:

import attr

@attr.s
class B(A):
    b: int = attr.ib()

The code seems to work:代码似乎有效:

import attr

class A:
    def __init__(self, a: int):
        self.a = a

attr.s(these={
    "a": attr.ib(type=str)
}, init=True)(A)

@attr.s(kw_only=True)
class B(A):
    b: int = attr.ib()

if __name__ == "__main__":
    a = A(1)
    b = B(a=1, b=2)
    print(a)  # output: A(a=1) 
    print(b)  # output: B(a=1, b=2)

but mypy/pyright is unhappy.但是 mypy/pyright 不高兴。

> mypy file.py
error: Unexpected keyword argument "a" for "B"

I'm reasonably sure that the MyPy attrs plugin doesn't support these .我有理由确定 MyPy attrs 插件不支持these .

Since you're not calling super , the idiomatic way would be to just define a as an attribute on B so that attrs takes care of it.由于您没有调用super ,惯用的方法是将a定义为B上的属性,以便 attrs 处理它。


JFTR: if you use @attr.define or @attr.s(auto_attribs=True) , you can leave out the attr.ib() call(s). JFTR:如果您使用@attr.define@attr.s(auto_attribs=True) ,则可以attr.ib()调用。

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

相关问题 如何在 Python 元类中键入 __new__ 方法,以便 mypy 满意 - How to type the __new__ method in a Python metaclass so that mypy is happy Mypy 为装饰 class 的子类返回错误“意外的关键字参数”,属性为 package - Mypy returns Error "Unexpected keyword argument" for subclass of a decorated class with attrs package 如何在 python-attrs 类中忽略额外的 kwargs - how to ignore extra kwargs in python-attrs class 如何通过cloudpickle腌制python-attrs类函数? - How to pickle python-attrs class functions via cloudpickle? __init__() 得到了一个意外的关键字参数“attrs” - __init__() got an unexpected keyword argument 'attrs' 带有额外参数的python-attrs中的自定义验证器 - Custom validator in python-attrs with extra parameters python-attrs:子类中的验证器 - python-attrs: validator in child class 有没有一种用`python-attrs`记录属性的好方法? - Is there a good way to document attributes with `python-attrs`? 如何解决 TypeError: __init__() got an unexpected keyword argument 'attrs' Django - How to resolve TypeError: __init__() got an unexpected keyword argument 'attrs' Django Django TypeError: __init__() 得到了一个意外的关键字参数“attrs” - Django TypeError: __init__() got an unexpected keyword argument 'attrs'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM