Decorator behavior

mhearne808[insert-at-sign-here]gmail[insert-dot-here]com mhearne808 at gmail.com
Fri Jul 22 16:38:32 EDT 2011


I am just trying to wrap my head around decorators in Python, and I'm
confused about some behavior I'm seeing.  Run the code below (slightly
adapted from a Bruce Eckel article), and I get the following output:

inside myDecorator.__init__()
inside aFunction()
Finished decorating aFunction()
inside myDecorator.__call__()

My question: Why isn't the first print statement in "__main__" the
first line of code executed?  Is aFunction() not closed somehow?

#!/usr/bin/env python

class myDecorator(object):
    def __init__(self, f):
        print "inside myDecorator.__init__()"
        f() # Prove that function definition has completed

    def __call__(self):
        print "inside myDecorator.__call__()"

@myDecorator
def aFunction():
    print "inside aFunction()"

if __name__ == '__main__':
    print "Finished decorating aFunction()"
    aFunction()



More information about the Python-list mailing list