Wednesday, April 15, 2009

Tracking Python function calls

It is sometimes useful to track the number of calls against a certain function in Python somewhere deep in the internals of the system. Turns out the Python global keyword can help with this.

Consider the following module:

### foo.py ###

def foo( ):
pass

### foo.py ###

Assuming that the foo module is imported at some point during execution with import foo or from foo import foo rather than being run as a script in its own right, the following use of global is possible:

### foo.py ###

visits = 0

def foo( ):
global visits
visits += 1
print 'visit number %s' % visits

### foo.py ###

Each call against foo( ) will now increment the global visits counter and print to standard out.

A not-bad use of global indeed.

No comments: