Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python attrs - positional attribute in super class while optional in sub class

I have 2 very similiar classes: A and B:

import attr
@attr.s
class A(object):
   x = attr.ib()
   y = attr.ib()

@attr.s
class B(object):
   x = attr.ib()
   z = attr.ib()
   y = attr.ib(default=None)

As you can see, they share 2 attributes (x and y), but in class A y attribute is positional while in B it's optional.

I want to group these classes in one super class, but if I try making class B inherit from class A I get the following error:

SyntaxError: duplicate argument 'y' in function definition

Added the code I used for raising the error:

@attr.s
class A(object):
    x = attr.ib()
    y = attr.ib()


@attr.s
class B(A):
    z = attr.ib()
    y = attr.ib(default=None)

So my question is: is it possible group these classes in one super class using attrs module? if no, would you suggest me just grouping them like the 'old fashion' way instead (implementing init methods on my own)?

Many thanks!

like image 349
NI6 Avatar asked Nov 09 '17 09:11

NI6


1 Answers

It’s not entirely clear to me what behavior you expect? If you want to overwrite A's y, I have good news because that should work in attrs 17.3 that has been released just yesterday:

>>> @attr.s
... class A(object):
...     x = attr.ib()
...     y = attr.ib()
...
...
... @attr.s
... class B(A):
...     z = attr.ib()
...     y = attr.ib(default=None)

>>> B(1, 2)
B(x=1, z=2, y=None)
like image 113
hynek Avatar answered Oct 22 '22 01:10

hynek