One feature of Python that I discovered by accident while looking through Django code is “python decorators” with which you can annotate your functions and classes. Details about the feature and it’s possible uses can be found here.
Here is an example decorator that I wrote:
def print_parameters(f):
def new_f(*args, **kwds):
print args
print kwds
return f(*args, **kwds)
new_f.func_name = f.func_name
return new_f
This decorator creates a new wrapper function, new_f. new_f prints args and kwds from the original function’s signature and then executes the original function. My decorator returns the new function, which replaces the original definition (func_name, the name of the function object, is changed to reflect the name of the original function instead of new_f).
And in action:
>>> @print_parameters
... def foo(a,b,c):
... print 'this is foo'
...
>>> foo(1,2,3)
(1, 2, 3)
{}
this is foo
>>> foo(1,2,c=3)
(1, 2)
{'c': 3}
this is foo