Python Inner Functions
In this tutorial, we will learn how to define, and how does these inner functions work.
In Python, you can define one or more functions inside a function. Functions inside a function are called inner functions.
Example
In this example, we will define a simple function with two inner functions.
Python Program
def function():
print('Inside function.')
def innerFunction1():
print('Inner function 1.')
def innerFunction2():
print('Inner function 2.')
innerFunction1()
innerFunction2()
function()
Run Code CopyThe naming for function(), innerFunction1() and innerFunction2() is for understanding purpose only. We may use our own function names based on the requirement.
Output
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().
- Execute print('Inside function.').
- Define innerFunction1().
- Define innerFunction2().
- Call innerFunction1().
- Execute print('Inner function 1.').
- Call innerFunction1().
- Execute 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 function(). So, innerFunction1() is visible only inside function(). We cannot call innerFunction1() outside function(). It is only when we call function(), innerFunction1() is defined. And after the execution of function(), innerFunction1() is no more defined. The same explanation holds for innerFunction2() as well.
Calling Inner Function from outside their scope
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.
Python Program
def function():
print('Inside function.')
def innerFunction1():
print('Inner function 1.')
def innerFunction2():
print('Inner function 2.')
innerFunction1()
innerFunction2()
innerFunction1()
Run Code CopyOutput
Traceback (most recent call last):
File "d:/pythonexamplesorg/example.py", line 13, in <module>
innerFunction1()
NameError: name 'innerFunction1' is not defined
Summary
In this tutorial of Python Examples, we learned how to define inner function(s) and their scope in a Python program.