How many times inner functions are compiled ?

Michael Hudson mwh21 at cam.ac.uk
Tue Jun 13 12:52:04 EDT 2000


"Tim Peters" <tim_one at email.msn.com> writes:

> [Jerome Quelin]
> > def outer():
> >     def inner():
> >         print "spam"
> >     inner()
> > outer()
> > outer()
> >
> > In the snippet code above, I call outer() two times. I would like to
> > know how many times python will compile the inner function ?  One time
> > when compiling the script/module, or two times, ie at every invocation
> > of the outer function ?
> 
> Just van Rossum gave you the best answer, but since he was out-voted 2 to 1
> I thought I'd jump in to even the odds <wink>.  "inner" is compiled exactly
> once, independent of how often "outer" is called (even if you never call
> outer, "inner" is compiled once).  However, the "def" stmt is executable in
> Python, and at runtime, each time "outer" is called, upon hitting the "def
> inner():" block the (pre)compiled code object for "inner" is wrapped up in a
> function object and bound to "outer"'s local vrbl name "inner".  The
> "function object" adds stuff like values for default arguments to the code
> object (but you don't have any default arguments in this example, so you'll
> have to use your imagination).

To illustrate with code:

>>> def outer():
...     def inner():
...         print "bob"
...     return inner
... 
>>> outer() is outer()
0
>>> outer().func_code is outer().func_code
1

Cheers,
M.

-- 
  how am I expected to quit smoking if I have to deal with NT 
  every day                                                -- Ben Raia



More information about the Python-list mailing list