meanburrito920
September 23rd, 2008, 04:52 AM
I've been hearing some stuff about decorators in python recently and I decided to check it out. However, I'm not sure I exactly understand how it works. For instance, I found this code snippet:
>>> def print_args(function):
>>> def wrapper(*args, **kwargs):
>>> print 'Arguments:', args, kwargs
>>> return function(*args, **kwargs)
>>> return wrapper
>>> @print_args
>>> def write(text):
>>> print text
>>> write('foo')
Arguments: ('foo',) {}
foo
I understand that it is passing the function write() into the function print_args(), but why does print_args return a function? does this basically just pass wrapper back through write() as the text arguement? It seems rather confusing, could anyone please shed some light on the concept?
>>> def print_args(function):
>>> def wrapper(*args, **kwargs):
>>> print 'Arguments:', args, kwargs
>>> return function(*args, **kwargs)
>>> return wrapper
>>> @print_args
>>> def write(text):
>>> print text
>>> write('foo')
Arguments: ('foo',) {}
foo
I understand that it is passing the function write() into the function print_args(), but why does print_args return a function? does this basically just pass wrapper back through write() as the text arguement? It seems rather confusing, could anyone please shed some light on the concept?