I'm working on a callback system in Python. The to-be callbacks are methods of a class. I register these with a decorator. Here is some pseudo class representing this:
class MyClass(ABC):
def __init__(self):
self.cb_stack = {}
def register_callback(self, callback, name):
self.cb_stack[name] = callback
@register_callback('mycb')
def myCallback(self, input):
self.do_things()
I suspect each decorator is executed by default.
I would like however for the decorator to be executed when obj.myCallback() is called, and to prevent myCallback() from executing at that moment (which should be the case here).
The alternative I have is to write it in the long form for each callback, which should work like so:
class MyClassLong(ABC):
def __init__(self):
self.cb_stack = {}
def register_callback(self, callback, name):
self.cb_stack[name] = callback
def myCallback(self):
def func(self, input):
self.do_things()
self.register_callback(func, 'mycb')
Notice it adds two lines of codes, so it's not really an issue but more how to make something clean. Does anyone knows how if it is achievable, and how ?
So both of your versions have an argument input that is ignored but to a different function both times, so I don't know what you want exactly, but if we take that out, you could simpy use:
class MyClass(ABC):
def __init__(self):
self.cb_stack = {}
def register_callback(self, callback, name):
self.cb_stack[name] = callback
def myCallback(self):
self.register_callback(self.do_things, 'mycb')
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