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"
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With