I am trying to decorate an @abstractmethod
in an abstract class (inherited by abc.ABC
in Python 3.9)
As a MWE,
from abc import ABC, abstractmethod
class Block(ABC):
def __init__(self,id=1):
self.id=id
@abstractmethod # the method I want to decorate
def run(self):
pass
def store_id(self,fun): # the decorator I want to apply to run()
def wrapper(fun):
id=fun()
self.id=id
return id
return wrapper
class Example(Block):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
def run(self):
print("I am running")
id=3
return id
t=Example()
t.run()
print(t.id)
I would like to decorate run()
so that the returned id
can be stored in the object without the end user to hardcode it.
I looked for the solution to this problem, the most complete being this one.
The __init_subclass__
magic method seems to be my best shot of using the method store_id
within Block
to decorate run()
after its concrete implementation.
However, if I override __init_subclass__
in Block
like this:
def __init_subclass__(self):
super().__init_subclass__()
self.run = self.store_id(self.run)
I get a TypeError
which I do not know how to fix:
TypeError: store_id() missing 1 required positional argument: 'fun'
.
Am I approaching this problem in the right way? Am I missing something fundamental a or is it something related to 'abc' type of classes?