Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this possible with decorators?

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?

like image 976
Lars Steen Avatar asked Dec 07 '25 06:12

Lars Steen


1 Answers

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()
like image 122
Martijn Pieters Avatar answered Dec 08 '25 19:12

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!