Python Inner Function / Nested Functions
Advertisement
Python offers many features and one such feature is that it has the ability to implement Inner Function or Nested Functions. In Simple terms, You can define a Function within another Function. Let’s Learn about Python Inner Function / Nested Function.
Python Inner Function
Inner Functions are useful when performing complex tasks more than once within another function. It also helps to avoid loops and code duplication.
def outerFunction(a, b):
def innerFunction(c, d):
return c*d
return innerFunction(a, b)
print(outerFunction(10, 20))
200
In the above code, the outer function is called with two integer arguments and the outer function has an inner function that calls and returns the inner function with the arguments of the outer function.
This feature in Python helps us to encapsulate the function.
If you try to call the inner function from the outside scope of the outer function.
def outerFunction(a, b):
def innerFunction(c, d):
return c*d
return innerFunction(a, b)
print(innerFunction(10, 20))
Traceback (most recent call last):
File ".\sr.py", line 7, in
print(innerFunction(10, 20))
NameError: name 'innerFunction' is not defined
Thus we can conclude that the inner function is encapsulated from the global scope.
DRY Principle (Don’t Repeat Yourself)
The Inner Function Feature also helps us to avoid code duplication and follows the DRY principle.
def wish(name):
def say(Quote):
return f"Good Morning, {name}"
return say(name)
print(wish("HTD"))
Good Morning, HTD
Inner Function Scope in Python
Python Inner Functions or Nested Functions can access the variables of the outer function as well as the global variables.
text = "Hey"
def wish():
name = "HTD"
def say():
quote = "Good Morning"
return f"{text} {quote}, {name}"
return say()
print(wish())
Hey Good Morning, HTD
The inner functions variable has a local scope that is limited only to that function. Inner Functions variables can’t be accessed at the outer function scope.
text = "Hey"
def wish():
name = "HTD"
def say():
quote = "Good Morning"
return f"{name}"
print(f"{text} {quote}")
return say()
print(wish())
Traceback (most recent call last):
File ".\sr.py", line 14, in
print(wish())
File ".\sr.py", line 10, in wish
print(f"{text} {quote}")
NameError: name 'quote' is not defined
Inner Function Local Variable
When the outer function and the inner function have a variable with the same name, the inner function variable creates a new variable with the same name.
def f1():
name = "HTD"
print("Id of Outer Function Variable ", id(name))
def f2():
name = "Hack The Developer"
print("Id of Inner Function Variable ", id(name))
return "Inner Function Call Successful!"
return f2()
print(f1())
Id of Outer Function Variable 2754042101360
Id of Inner Function Variable 2754038145392
Inner Function Call Successful!
Both the id are different which shows both the variable holds different memory locations and thus are scoped within the function.
Non Local Variable
From the above section, we saw inner function creates its own variable if the name matches. Let’s see how we can access the outer function variable inside the inner function using nonlocal.
def f1():
name = "HTD"
def f2():
nonlocal name
name = "Hack The Developer"
print("Id of Inner Function Variable ", id(name), name)
return "Inner Function Call Successful!"
f2()
print("Id of Outer Function Variable ", id(name), name)
f1()
Id of Inner Function Variable 2445877269168 Hack The Developer
Id of Outer Function Variable 2445877269168 Hack The Developer
Id Value of both the variable is the same, this specifies that we are using the same variable in the inner as well as the outer function.
The Inner Function uses the nonlocal to specify that we want to use the variable present in the outer function. When the value of the variable is changed in the inner function, it also modifies the outer function’s variable because of the nonlocal assignment.
Learn about List Comprehension in Python, a better way to create a list in only a single line.
Hope you like it!
Learn more about inner function or nested function from realpython.