I am trying to get a class decorator working. The decorator will add a __init_subclass__
method to the class it is applied to.
However, when the method is added to the class dynamically, the first argument is not being bound to the child class object. Why is this happening?
As an example: this works, and the static code below is an example of what I'm trying to end up with:
class C1:
def __init_subclass__(subcls, *args, **kwargs):
super().__init_subclass__(*args, **kwargs)
print(f"init_subclass -> {subcls.__name__}, {args!r}, {kwargs!r}")
Test:
>>> D = type("D", (C1,), {})
init_subclass -> D, (), {}
However if I add the __init__subclass__
method dynamically, the child class is not being bound to the first argument:
def init_subclass(subcls, **kwargs):
super().__init_subclass__(**kwargs)
print(f"init_subclass -> {subcls.__name__}, {args!r}, {kwargs!r}")
def decorator(Cls):
Cls.__init_subclass__ = init_subclass
return Cls
@decorator
class C2:
pass
Test:
>>> D = type("D", (C2,), {})
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: init_subclass() missing 1 required positional argument: 'subcls'
Why is this happening and how can I do this and get the binding to work the right way?