Hi there,
I use a certain base class. Then, every subclass of this base inherits all the functionalities without problem.
My issue now comes from the fact that I tried turning this into a decorator for cleaner syntax and got a weird problem with super()
.
After many tries I wasn’t able to debug so I give you a minimal example here:
class BaseClass: ... # The base class
def baseclass(cls): # The decorator
"""To emulate subclassing BaseClass."""
return type(cls.__name__, (BaseClass,) + cls.__bases__, dict(cls.__dict__))
class SubClass(BaseClass):
def __init__(self):
super().__init__()
@baseclass
class Decorated:
def __init__(self):
super().__init__()
@baseclass
class DecoratedWithArguments:
def __init__(self):
super(type(self), self).__init__() # Helping `super()`
This approach works perfectly for everything I needed except… the use of super()
. Indeed, I get the following:
>>> SubClass()
<__main__.SubClass object at 0x00000241942C2D50>
>>> DecoratedWithArguments() # Works when `super()` gets help
<__main__.DecoratedWithArguments object at 0x000002419416E210>
>>> Decorated() # Doesn't work without arguments specification
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in __init__
TypeError: super(type, obj): obj must be an instance or subtype of type
I’ve looked a both the MRO
and __bases__
inside corresponding all three __init__
:
SubClass:
MRO: [<class '__main__.SubClass'>, <class '__main__.BaseClass'>, <class 'object'>]
bases: (<class '__main__.BaseClass'>,)
DecoratedWithArguments
MRO: [<class '__main__.DecoratedWithArguments'>, <class '__main__.BaseClass'>, <class 'object'>]
bases: (<class '__main__.BaseClass'>, <class 'object'>)
Decorated
MRO: [<class '__main__.Decorated'>, <class '__main__.BaseClass'>, <class 'object'>]
bases: (<class '__main__.BaseClass'>, <class 'object'>)
I’m completely desperate, the only difference I could find is there, with __bases__
containing object
when I manually use type
(decorator approach). I naively tried to remove it indice baseclass
definition, to no avail.
If anyone has any insight, it’d be greatly appreciated!!
In advance, thank you!