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.
You can check the bytecode with the
dis
module: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 thedef little_function
is executed every timemy_function
is called), but this doesn't add much overhead.The code in the inner function is compiled only once, so there shouldn't be a significant runtime penalty.
Only inner's function closure gets updated each time the outer function is called. See here, for example, for more details about closures.
Here's a quick demonstration, examining the closure: