Wednesday, September 3, 2014

Decorator for easier callback handling

Sometimes you may want a function to be called and process the return of a previous function, this is how to do it easily with a decorator.

def register(proceeding_func):
    import functools
    def actualDecorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            return proceeding_func(func(*args, **kwargs))
        return wrapper
    return actualDecorator

And here is how to use it:

if __name__ == '__main__':
    from time import sleep
    def func2(string):
        print("after {string}, I did something".format(string = string))

    @register(func2)
    def func1(a):
        sleep(5)
        return "dealing with {a}".format(a = a)

    func1(3)

Written with StackEdit.