Thursday, May 10, 2007

Python decorators a simple example

Python decorators are a wonderful syntax for wrapping one function in another. I had a bit of trouble understanding the documentation, which often seems to involve talking about the history of how the syntax evolved rather than cutting to the chase and giving a simple example.

Specifically, I wanted to know how to get access to the arguments to the function I'm decorating in the decorator. Here's my example, at the top is the output:


"""
Example decorator that gets function arguments.

>>> decotest.py

>in mydecorator
>Function decorateme has been wrapped
> args = hello this is request
> kwargs = {}
>request = hello this is request
decorateme got request = hello this is request
>finished wrapped function
"""

def mydecorator(f):
print ">in mydecorator"
def wrapper(*args, **kwargs):
print ">Function %s has been wrapped" % f.__name__
print "> args = %s" % args
print "> kwargs = %s" % kwargs
request = args[0]
print ">request = %s" % request
f(*args, **kwargs)
print ">finished wrapped function"
return wrapper


def test():
request = "hello this is request"
decorateme(request)

@mydecorator
def decorateme(request):
print "decorateme got request = %s" % request

if __name__ == "__main__":
test()

No comments:

Post a Comment