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
def outerFunction(a, b):
def innerFunction(c, d):
return c*d
return innerFunction(a, b)
print(outerFunction(10, 20))
Output:
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 outer function.
Calling Inner Function.
def outerFunction(a, b):
def innerFunction(c, d):
return c*d
return innerFunction(a, b)
print(innerFunction(10, 20))
Error:
Traceback (most recent call last):
File ".\sr.py", line 7, in <module>
print(innerFunction(10, 20))
NameError: name 'innerFunction' is not defined
Thus we can conclude that the inner function is encapsulated from global scope.
DRY Principle (Don’t Repeat Yourself)
The Inner Function Feature also helps us to avoid the code duplication and follows the DRY principle.
def wish(name):
def say(Quote):
return f"Good Morning, {name}"
return say(name)
print(wish("HTD"))
Output:
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())
Output:
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.
Learn more from the original post: Python Inner Function
Read more on Python.
Top comments (0)