Generators and Decorators doing my head in ..

Leif K-Brooks eurleif at
Tue Sep 6 18:13:16 CEST 2005

simonvc at wrote:
> Im trying to create a decorator that counts the number of times a
> function is run.

Your code doesn't work because decorators are run at function creation
time, not at function run time. Try this instead:

from itertools import count

def logFunctionCalls(function):
    times = count()
    def newfunction(*args, **kwargs):
        print "Entering function:", function.__name__,
        return function(*args, **kwargs)
    newfunction.__doc__ = function.__doc__
    newfunction.__name__ = function.__name__
    return newfunction

def doWork():
    print "Doing work..."

More information about the Python-list mailing list