Decorator behavior

Ian Kelly ian.g.kelly at gmail.com
Fri Jul 22 16:59:50 EDT 2011


On Fri, Jul 22, 2011 at 2:38 PM,
mhearne808[insert-at-sign-here]gmail[insert-dot-here]com
<mhearne808 at gmail.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?

Because everything in the module is executed in order.  First the
myDecorator class is defined.  Then the aFunction function is defined
and the decorator is applied to it (which involves calling the
decorator).  Finally the if condition is tested, and if it's true, the
"Finished decorating" string is printed and the decorated function is
called.

If this module were not the main module, the exact same thing would
happen, except that the if would evaluate false, and so that part of
the code would be skipped.

By the way, your email address is not mangled.  The label part looks
like a mangled email, but the actual address part is intact.



More information about the Python-list mailing list