Python Inner Functions
In Python, you can define one or more functions inside a function. Functions inside a function are called inner functions.
In this tutorial, we will learn how to define and how does these inner functions work.
In this example, we will define a simple function with two inner functions.
def function(): print('Inside function.') def innerFunction1(): print('Inner function 1.') def innerFunction2(): print('Inner function 2.') innerFunction1() innerFunction2() function()
The naming for
innerFunction2() is for understanding purpose only. We may use our own function names based on the requirement.
Inside function. Inner function 1. Inner function 2.
In the above program, we have function() which has a print statement, then two inner functions namely innerFunction1() and innerFunction2(), and then we called these inner functions.
After defining the function(), we called the function using function().
Working of Inner Functions
Now, let us understand the execution of a function with inner functions. We will take the above program for example.
We know that the program execution happens sequentially. Following is the step by step execution of the above program.
- Define function().
- Call function().
- Define innerFunction1().
- Define innerFunction2().
- Call innerFunction1().
print('Inner function 1.').
- Call innerFunction1().
print('Inner function 2.').
Now, we will observe the scope of our
function() and inner functions.
function() is defined in the scope of program. So, you can access
function() anywhere in the program.
innerFunction1() is defined inside
innerFunction1() is visible only inside
function(). We cannot call
function(). It is only when we call
innerFunction1() is defined. And after the execution of
innerFunction1() is no more defined. The same explanation holds for
innerFunction2() as well.
If you try to call any of the inner function from outside their scope, NameError is raised during function call. We have demonstrated the same in the following example.
def function(): print('Inside function.') def innerFunction1(): print('Inner function 1.') def innerFunction2(): print('Inner function 2.') innerFunction1() innerFunction2() innerFunction1()
Traceback (most recent call last): File "d:/pythonexamplesorg/example.py", line 13, in <module> innerFunction1() NameError: name 'innerFunction1' is not defined
In this tutorial of Python Examples, we learned how to define inner function(s) and their scope in a Python program.