Generators and Decorators doing my head in ..

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


simonvc at gmail.com 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__, times.next()
        return function(*args, **kwargs)
    newfunction.__doc__ = function.__doc__
    newfunction.__name__ = function.__name__
    return newfunction

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



More information about the Python-list mailing list