adding new functionality to a function non-intrusively!

Michele Simionato michele.simionato at gmail.com
Wed Feb 16 10:03:07 EST 2005


Decorators are your friends. You can wrap a function
and give it additional functionality. For instance just
yesterday I needed to keep track of how many times
a function is called. This can be done with this
decorator:

.def with_counter(f):
.    def wrappedf(*args, **kw):
.        wrappedf.counter += 1
.        return f(*args, **kw)
.    wrappedf.counter = 0
.    wrappedf.func_name = f.func_name
.    return wrappedf

. at with_counter # requires Python 2.4
.def g():
.    print "called"

.print g.counter
.g()
.print g.counter

This is intented just as an appetizer. Look at the
cookbook for more examples.

                  Michele Simionato




More information about the Python-list mailing list