Python’s decorator is a powerful tool to wrap (decorate) functions, such as add some pre-processing steps before the function, or post-processing steps after it. This following example is modified based on the example from the functools doc page, and perfectly illustrated two important points, as marked in red below.
from functools import wraps def my_decorator(f): @wraps(f) def wrapper(*args, **kwds): """Docstring of wrapper""" print 'Calling decorated function' return f(*args, **kwds) return wrapper @my_decorator def example(foo): """Docstring of example""" print 'Called example function' return(foo+1) print(example(2)) print(example.__name__) print(example.__doc__)
Calling decorated function Called example function 3 example Docstring of example
- If wraps(f) were not called, then the output lines 4 and 5 would be “wrapper” and “Docstring of wrapper”. (Of course generally you would not write a docstring for the wrapper function)
- If return were not used, the output line 3 would be “None”.