python function decorators

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):
    def wrapper(*args, **kwds):
        """Docstring of wrapper"""
        print 'Calling decorated function'
        return f(*args, **kwds)
    return wrapper

def example(foo):
    """Docstring of example"""
    print 'Called example function'

 The output should be:
Calling decorated function
Called example function
Docstring of example
  1. 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)
  2. If return were not used, the output line 3 would be “None”.



python function decorators

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s