Understanding Closures in Python

Posted by Afsal on 16-Feb-2024

Hi Pythonistas!

Today we will learn another advanced topic in python which is closures. Consider the case where inner and outer functions. Inner function remembers the outer function variable, this is called closures. Let us explain this with an example

def adder(a):
    def inner(b):
        return a + b
    return inner

In [34]: five_adder = adder(5)

In [35]: five_adder(1)
Out[35]: 6

In [36]: five_adder(2)
Out[36]: 7

In [38]: ten_adder = adder(10)

In [39]: ten_adder(1)
Out[39]: 11

In [42]: ten_adder(2)
Out[42]: 12

In [43]: five_adder(5)
Out[43]: 10

We can see that the variable a is in the outer function and b in the inner function. When adder(5) is called then value if a is remembered by the inner function. Then when we call five_adder(1) previous 5 and 1 get added and we get 6 as the result. Even if we creates the another instance of the function they remain independent

Closures are help for creating 

  • Creating different function on the go, like the example
  • Data encapsulation
  • Closures are handy for creating callback functions that remember the context in which they were created.
  • Decorators use these variables

I hope you have learned a new concept from this post. Please share your valuable suggestions with afsal@parseltongue.co.in