Generators and Decorators doing my head in ..

Paul McGuire ptmcg at austin.rr.com
Tue Sep 6 11:52:20 EDT 2005


Compare this to your original:

def logFunctionCalls(function):
    ec = FunctionCounter()
    def decoratedFunction(*args,**kwargs):
        print "Entering function:", function.__name__, ec.next()
        function(*args,**kwargs)
    return decoratedFunction

@logFunctionCalls
def doWork():
    print "Doing Work"

doWork()
doWork()

(This is a quick-and-dirty example, but it works.  A proper iterator
would do more to preserve the identity, docstring, etc. of the
underlying doWork() function.  See the decorator library page on the
Python Wiki, at http://wiki.python.org/moin/PythonDecoratorLibrary.)

Also, look into the treasure trove that is itertools, especially
itertools.count.

-- Paul




More information about the Python-list mailing list