Search code examples
pythonperformanceclosuresnested-function

Function inside function - every time?


Let we have this code:

def big_function():
    def little_function():
         .......
    .........

The Python documentation says about def statement:

A function definition is an executable statement. Its execution binds the function name...

So, the question is: Does def little_function() execute every time when big_function is invoked? Question is about def statement exactly, not the little_function() body.


Solution

  • You can check the bytecode with the dis module:

    >>> import dis
    >>> def my_function():
    ...     def little_function():
    ...             print "Hello, World!"
    ...     
    ... 
    >>> dis.dis(my_function)
      2           0 LOAD_CONST               1 (<code object little_function at 0xb74ef9f8, file "<stdin>", line 2>)
                  3 MAKE_FUNCTION            0
                  6 STORE_FAST               0 (little_function)
                  9 LOAD_CONST               0 (None)
                 12 RETURN_VALUE  
    

    As you can see the code for the inner function is compiled only once. Every time you call my_function it is loaded and a new function object is created(in this sense the def little_function is executed every time my_function is called), but this doesn't add much overhead.