So I have this following code:
from collections import defaultdict
_event_handlers = defaultdict(set)
def add_event_handler(event_name=""):
def wrapper(func):
_event_handlers[event_name if event_name else func.__name__].add(func)
return func
return wrapper
@add_event_handler()
def bar():
print("test")
class Foo:
def __init__(self, f):
self.f = f
@add_event_handler()
def bar(self):
print(self.f)
def dispatch_event(event_name, **kwargs):
for handler in _event_handlers[event_name]:
handler(**kwargs)
test = Foo(5)
dispatch_event("bar")
I'm trying to develop an event system which allows you to registered an event with the @add_event_handler()
decorator which adds the method to a global _event_handlers
variable and then events can be dispatched using that. However, it works for global methods, but not for methods in a class as a TypeError
is raised since self
is not provided. How can I fix this?