Search code examples
pythondecoratorpython-decorators

Why doesn't this python decorator work?


I'm trying to understand decorators in python. I don't understand why the following doesn't work:

def decorator(func):
    def logger(*args, **kwargs):
        print "start logging"
        func(*args, **kwargs)
        print "end logging"
    return logger

@decorator
def add(a,b):
    return a+b

If I call add(2,3) the output will be:

start logging
end logging

However if I modify my code and write return func(*args, **kwargs) in the definition of logger it works but then end logging is not written on the output.


Solution

  • You can capture the return value in a variable, and return it after printing:

    def decorator(func):
        def logger(*args, **kwargs):
            print "start logging"
            result = func(*args, **kwargs)
            print "end logging"
            return result
        return logger
    

    Decorators are not special here; it's just a function calling another function.