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