Reputation: 759
I'm new to python and I'm exploring my way through the language while building real applications. Right now I'm trying to build an event-based app, and was thinking about using decorators as a way to add functions as listeners:
@onEvent(eventSpecificArgument)
def foo():
print('foo')
In the above example, I have added the function foo as a listener for the event, and have passed an argument that will be used by the decorator.
Is this a possible (and smart enough) solution for what I want? And if it is, how could/should I implement it?
Upvotes: 3
Views: 245
Reputation: 1122482
Sure, decorators are just callables. Decorator notation is just syntactic sugar, your example translates to:
def foo():
print('foo')
foo = onEvent(eventSpecificArgument)(foo)
so your onEvent()
callable needs to return something that can be called; that 'something' will be passed in foo
.
Whatever you do in onEvent
and in the 'something' it returned is up to you.
Something like the following would work:
registry = {}
def onEvent(eventname):
def eventdecorator(func):
registry.setdefault(eventname, []).append(func)
return func
return eventdecorator
This just adds func
to the registry for a given eventname and returns the function unchanged.
Later on, when you then need to handle the event, you just look up the event handlers for that event with:
for func in registry.get(eventname, ()):
func()
Upvotes: 4