Inner Functions in Python

In this article, we will learn about the inner functions in Python. So, now let’s discuss what is the inner function? How does it work in python? We will discuss these whole things accordingly.

What is Inner Function?

A function inside a function is known as an inner function. It is the concept of Encapsulation. Encapsulation is the process of binding of data and properties to a single unit. We can use the inner function to protect it from the outside of the function.

How we can use Inner Function in Python?

Let’s do an example. It will help to understand the basic concept of this topic.


def outer(num1):
    def inner_increment(num1):  
        return num1 + 1
    num2 = inner_increment(num1)
    print(num1, num2)



10 11


Now, we will explain this whole program and the logic behind it. First of all, it has one function “outer” which has an argument called “num1”. The main purpose of the program is to increment the value i.e. if I will give 5, it will return 6(5 + 1 = 6). So, now we have also initialized one function inside the outer function which is “inner_increment” function. This function is used to increment the value. This function is protected from all the outside environment. This inner_increment is called an inner function being inside of a function.

We will do another program to understand better.


import logging  
logging.basicConfig(filename ='example.log', level = logging.INFO)  
def logger(func):  
    def log_func(*args):   
            'Running "{}" with arguments {}'.format(func.__name__, args))  
    return log_func                
def add(x, y):  
    return x + y  
def sub(x, y):  
    return x-y  
add_logger = logger(add)  
sub_logger = logger(sub)  
add_logger(3, 3)  
add_logger(4, 5)  
sub_logger(10, 5)  
sub_logger(20, 10)



You can also go through this nested function in Python for more experience.

Leave a Reply
