Python Closures Explained

Python Closures Explained

Hey everyone! Today, we're diving into an advanced concept in using functions called closure. A closure is a programming technique where an inner function is returned from an outer function, allowing you to capture and reuse the outer function's variables even after the outer function has exited.

Let's walk through an example. I have a function that contains a variable initialized to zero and an inner function. The increment function will add a value of one to the count variable. When we return this increment function, the count variable is captured and saved in a closure. This means the count variable can still be accessed through the increment function from outside the outer function.

Now, let's call the outer function to get the increment function. At this point, a closure is created and bound to the increment function. If we call increment four times, the count variable in the closure will be four. To confirm this, we can create another inner function that returns the count variable and return both this new function and the increment function as a tuple from the outer function. By calling the new function from outside, we can print the value of count and see that it's four, because each call to the returned function works with the same count variable from the same closure.

If we call the outer function again, it will return the same functions but with a new closure, similar to creating a new instance of a class where count acts like a private attribute accessible only through the returned functions.

def init():
    count  = 0
    def increment():
        nonlocal count
        count += 1
    def getcount():
        return count
    return increment, getcount

increment, getcount = init()

increment()
increment()
increment()
increment()

print(getcount())

increment1, getcount1 = init()

increment1()
increment1()
print(getcount1())

  • Date: