Monday, March 7, 2011

decorator

Definition
A decorator is a function whose primary purpose is to wrap another function or class.
Purpose
The primary purpose of this wrapping is to transparently alter or enhance the behavior
of the object being wrapped.
Basic usage
Syntactically, decorators are denoted using the special @ symbol as follows.  More than one decorator can also be applied.
@trace1
@trace0
def square(x):
    return x*x
The preceding code is shorthand for the following:
def square(x):
    return x*x
square = trace1(trace0(square))

Using parameters
A decorator can also accept arguments. Here’s an example:
@eventhandler('BUTTON')
def handle_button(msg):
    ...
The semantics of the decorator are as follows:
def handle_button(msg):
    ...
temp = eventhandler('BUTTON') # Call decorator with supplied arguments
handle_button = temp(handle_button) # Call the function returned by the decorator

Class decorator
Decorators can also be applied to class definitions. For example:
@foo
class Bar(object):
    def __init__(self,x):
        self.x = x
    def spam(self):
        statements

For class decorators, you should always have the decorator function return a class object
as a result.

No comments: