nested functions

Kent Johnson kent at
Thu Jun 15 22:12:19 CEST 2006

Fredrik Lundh wrote:
> George Sakkis wrote:
>> It shouldn't come as a surprise if it turns out to be slower, since the
>> nested function is redefined every time the outer is called.
> except that it isn't, really: all that happens is that a new function object is created from
> prebuilt parts, and assigned to a local variable.  it's not slower than, say, a method call.

Interesting. So func_code for a nested function is created when the 
module is compiled, and stuck in a new function object when the 
definition is executed. Like George, I always assumed that the body of 
the nested function was compiled when the outer function was executed, 
but that doesn't really make any sense - the *code* for the inner 
function is static, just the environment changes (globals(), closure).

dis.dis reveals all:

In [10]: def g():
    ....:     def h():
    ....:         print 'foo'
    ....:     return h

In [11]: dis.dis(g)
   2           0 LOAD_CONST               1 (<code object h at 00E8D960, 
file "<ipython console>", line 2>)
               3 MAKE_FUNCTION            0
               6 STORE_FAST               0 (h)

   4           9 LOAD_FAST                0 (h)
              12 RETURN_VALUE

Thanks Fredrik!

More information about the Python-list mailing list