Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 872
dondublon Avatar asked Apr 16 '13 07:04

dondublon


People also ask

Can you have functions inside functions?

A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.

Can you define a function within a function?

If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.

Can we write function inside function in Python?

A function which is defined inside another function is known as inner function or nested functio n. Nested functions are able to access variables of the enclosing scope. Inner functions are used so that they can be protected from everything happening outside the function.

How do you call a function repeatedly in Python?

start() and stop() are safe to call multiple times even if the timer has already started/stopped. function to be called can have positional and named arguments. You can change interval anytime, it will be effective after next run. Same for args , kwargs and even function !


1 Answers

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.

like image 188
Bakuriu Avatar answered Oct 14 '22 04:10

Bakuriu