Day 25: Exploring Python Closures

Day 25: Exploring Python Closures

ยท

2 min read

Welcome back !!! Today, we'll be learning an important concept in Python programming: closures.

What are Closures?

In Python, a closure is a nested function that holds access to variables from its enclosing scope even after the outer function has finished execution. This means that a closure "closes over" the environment in which it was defined, capturing and holding the values of variables from that environment.

How Closures Work

To understand closures, let's look at a simple example:

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

closure = outer_function(1)
print(closure(9))  # Output: 10

In this example, outer_function returns inner_function, which adds x (from the outer scope) to y. Even though outer_function has finished executing, inner_function still retains access to x. This is because inner_function forms a closure over the environment of outer_function.

Here's what the code execution looks like:

def outer_fun(name):
    text = name 
    def inner_fun():
        print(text)
    return inner_fun

example = outer_fun("hello im out")
example()
  • When outer_fun is called with the argument "hello im out", it creates a local variable text inside its scope and assigns it the value "hello im out".

  • The inner function inner_fun is defined within outer_fun and references the text variable from its enclosing scope.

  • Finally, outer_fun returns the inner function inner_fun.

Now, let's examine the line:

example = outer_fun("hello im out")
  • Here, example is assigned the value returned by outer_fun, which is the inner function inner_fun.

  • However, crucially, inner_fun holds access to the text variable from the scope of outer_fun. This means that even though outer_fun has finished executing and its local variables should technically be out of scope, inner_fun still "remembers" the value of text.

  • This behavior makes inner_fun a closure, as it "closes over" the environment of its enclosing function (outer_fun), capturing and retaining access to variables from that environment.

So, in summary, this line emphasizes that inner_fun (assigned to example) becomes a closure because it maintains access to the text variable from the enclosing scope of outer_fun, even after outer_fun has completed execution.

Conclusion

Closures are a powerful feature of Python that allows functions to retain access to variables from their enclosing scopes. They enable flexible and modular code design, enhancing the capabilities of Python programming.

Happy coding! ๐Ÿโœจ

ย