We can do a lot with functions like passing a function as an argument to another function, calling a function from another function, etc. In Python, we can also create a function inside another function. Show Table of Contents
A function which is created inside another function is called a nested function or an inner function. In this chapter, we will read about nested functions and their significance. Defining a Nested FunctionA nested function is defined by
simply creating it using the def keyword inside another function. Here is an example. def outer(): # outer function print("This is outer function") def inner(): print("This is inner function") inner() # calling inner function outer() # calling outer function Output This is outer function We defined a function named When the Note that an inner function is always called from inside the function in which it is defined. Thus, to call the inner function, we need to call the outer function. A nested function can access the variables defined in the function in which it is created. This is demonstrated in the following example. def outer(): # outer function x = 10 def inner(): print("Inside inner func", x) inner() # calling inner function print("Inside outer func", x) outer() # calling outer function Output Inside inner func 10 In this example, we defined a variable x having a
value of 10 in the So, from the above examples you must have understood that nested functions are just normal functions which are defined and called inside some other function. Let’s see one more example. def find_power(num): # outer function def power(n): return num ** n return power(2) # calling inner function and returning the value returned by it print(find_power(10)) # calling outer function Output This was a straight forward example. The Significance of Nested FunctionsThere can
be many reasons to use nested functions. Let’s see some of them. Nested functions can serve as helper functions of the function in which they are defined. Let’s see an example in which a nested function serves as a helper function for its parent function. def print_even(lst): def find_even(num): if num % 2 == 0: return True else: return False new_list = [] for num in lst: if find_even(num) == True: new_list.append(num) print("Final list:", new_list) mylist = [1, 2, 4, 5, 6, 7, 10, 11, 12] print_even(mylist) Output Final list: [2, 4, 6, 10, 12] Here the function Inside the Another use case of nested functions can be seen from the following example. def get_factorial(num): def factorial(num): if num == 0 or num == 1: return 1 else: return num * factorial(num - 1) if not isinstance(num, int): raise TypeError("Failed! The value must be a number") if num < 0: raise ValueError("Failed! The number must be non-negative") return factorial(num) print(get_factorial(5)) Output In the above example, the Now suppose if the code for both error handling and factorial calculation was written in the So by now, you must have got an idea of when you can use nested functions to reduce the complexity of your functions. Let’s look at some more cases when nested functions can be used. Sometimes
we might want to prevent some function from being directly accessed from anywhere in your program. In that case, we can put that function (say But why would we encapsulate a function?To answer that, let’s take a use case where we want to predict if a company will get profit or loss. Suppose we have a function which contains a logic that calculates the expected profit of a company. This logic might contain some information which we don’t want anyone to know. If we don’t want any other part of the program to directly access the logic in this function, we can put it as a nested function inside another function. Look at the following function structure. def profit_or_loss(): def get_profit(): # calculates profit return profit if profit > 0: return "Profit" else: return "Loss" profit_or_loss() Suppose Nested functions are also used for creating closures. We will read about closures in Closures. Now that you understand what nested functions are and where to use them, start including them in your programs wherever necessary. To learn from simple videos, you can always look at our Python video course on CodesDope Pro. It has over 500 practice questions and over 20 projects. Life is 10% what happens to us and 90% how we react to it. - Dennis P. Kimbro How do you call an inner function from the outside function in Python?If you need to access the function "b" which is inside another function "a" and you want to access it from the function "c", then you should define "b" in a scope that both "a" and "c" can see and use it. Can you call a nested function outside a function?Nested function is private to containing function Only the containing function can access the nested function. We cannot access it anywhere outside the function. This is because the inner function is defined in the scope of the outer function (or containing function). Can you access inner function Python?You cannot, not unless fib returns inner somehow. inner is essentially a local variable inside the scope of fib and you can't access a function's locals from outside of it. How do you call a nested function in Python?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. |