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):
    @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__)
 The output should be:
Calling decorated function
Called example function
3
example
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”.

 

 

Advertisements
python function decorators

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s