Skip to main content

Python Closures

In Python, Closures are the inner functions that are enclosed within the outer function. It can easily access variables present in the outer function scope. It can also access variables even after the execution of outer function has completed.

The method in which binding of data to a function without actually passing it as a parameters is called closure. It can avoid use of global variables. It also provide some form of data hiding.

It is a function object that remembers values in enclosing scopes even if they are not present in memory. It is the technique in which some data gets attached to the code.

Example:

def func_1(a):
    def func_2(b):
        return a + b
    return func_2

x = func_1(3)
y = func_1(5)
print(x(2))
print(y(10))
print(x(y(2)))

Output:

5
15
10
Tags
Submitted by devanshi.srivastava on August 3, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.