Decorator behavior

Dave Angel davea at ieee.org
Fri Jul 22 20:05:01 EDT 2011


On 01/-10/-28163 02:59 PM, 
mhearne808[insert-at-sign-here]gmail[insert-dot-here]com wrote:
> 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()
>
classes and functions and decorators have some portions that execute 
when they occur, long before anybody "calls" them.  (I'm sure there are 
other examples;  one might consider imports the same way)

In the case of classes, anything outside of the method definitions will 
happen before the class definition is completed. For example, class 
attributes happen at that time.

For functions/methods, default arguments are evaluated at the definition 
time.  So if the default value makes a call, the call will happen at 
that time.

Function decorators execute right after the corresponding function 
definition is built.  Such decorators won't normally call the function, 
but as you notice, if you do call it, it will execute.

When you think about it, these behaviors are the only reasonable way 
these things could be done, unless the compiler tried to do some "just 
in time" compiling, not really building the code till somebody uses it. 
And that would make the language a lot different.

DaveA





More information about the Python-list mailing list