How many times inner functions are compiled ?

Tim Peters tim_one at email.msn.com
Tue Jun 13 12:39:24 EDT 2000


[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).

yet-another-reason-python-isn't-a-democracy<wink>-ly y'rs  - tim






More information about the Python-list mailing list