Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #10159
| Date | 2011-07-22 20:05 -0400 |
|---|---|
| From | Dave Angel <davea@ieee.org> |
| Subject | Re: Decorator behavior |
| References | <8a7d158b-bc27-442c-9886-1a704d0c52e1@a11g2000yqm.googlegroups.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1394.1311379507.1164.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
Decorator behavior "mhearne808[insert-at-sign-here]gmail[insert-dot-here]com" <mhearne808@gmail.com> - 2011-07-22 13:38 -0700 Re: Decorator behavior Ian Kelly <ian.g.kelly@gmail.com> - 2011-07-22 14:59 -0600 Re: Decorator behavior Dave Angel <davea@ieee.org> - 2011-07-22 20:05 -0400
csiph-web