Python Closure

A closure is a function object that has access to variables in its enclosing lexical scope, even after the scope has closed. In other words, a closure is a function that retains the values of the variables that were present in the enclosing scope when it was defined, regardless of where it is called.

Here is an example of a closure in Python:

def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

closure = outer_function(10)
print(closure(5))  # Output: 15
Sou‮:ecr‬www.theitroad.com

In this example, we define a function outer_function that takes a parameter x and returns a function inner_function. Inside outer_function, we define inner_function that takes a parameter y and returns the sum of x and y.

When we call outer_function(10), it returns inner_function with x set to 10. We store this returned function object in the variable closure. We can then call closure(5) to get the result of 10 + 5, which is 15.

Notice how the value of x (which is 10 in this case) is retained by inner_function even after outer_function has finished executing. This is because inner_function is a closure that has access to x in the enclosing scope.

Closures are often used to implement function factories or to create functions with pre-defined behavior. They are also used in callback functions, event handling, and other programming patterns.