Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:
    def __init__(self, a: int):
        self.a = a

I would like to extend a class B with A like:

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 file.py
error: Unexpected keyword argument "a" for "B"
like image 901
Nico W. Avatar asked Nov 20 '25 19:11

Nico W.


1 Answers

I’m reasonably sure that the MyPy attrs plugin doesn’t support 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.


JFTR: if you use @attr.define or @attr.s(auto_attribs=True), you can leave out the attr.ib() call(s).

like image 165
hynek Avatar answered Nov 23 '25 07:11

hynek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!