In my Python application, I use events to communicate between different plugins. Now, instead of manually registering methods for events, I thought that I could use decorators for this.
I would like it to look like this:
@events.listento('event.name') def myClassMethod(self, event): ...
At first I tried to do it as follows:
def listento(to): def listen_(func): myEventManager.listen(to, func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return func return listen_
When I call myEventManger.listen('event', self.method) from the instance, everything works fine. However, if I use the decorator approach, the self argument is never passed.
Another approach that I tried, after searching for a solution on the Internet, was to use the class as a decorator:
class listen(object): def __init__(self, method): myEventManager.listen('frontend.route.register', self) self._method = method self._name = method.__name__ self._self = None def __get__(self, instance, owner): self._self = instance return self def __call__(self, *args, **kwargs): return self._method(self._self, *args, **kwargs)
The problem with this approach is that I really do not understand the concept of __get__ and that I do not know how to enable the parameters. Just for testing, I tried to use a fixed event for listening, but with this approach nothing happens. When I add print instructions, I see that __init__ is being called. If I add additional logging of "old-style" events, both __get__ and __call__ , and this event works despite the new decorator.
What would be the best way to achieve what I'm looking for, or am I just missing some important concept with decorators?