Python Closures

Python Closures are related to nested functions(a function defined inside another function). As we have discussed in the previous blog, nested functions can access the variables from the enclosing scope that can be modified using the nonlocal keyword.

You cannot call these variables outside their scopes but closure remembers these values even if they are not present in the memory.

Now, let’s see how to define a closure

Here, the enclosing function returns the nested function instead of calling it. This returned function was bound to name_closure. On calling name_closure(), the name was still remembered although we had already finished executing the enclosing function.

This can be used for data hiding and a substitute for classes if we have only one method in the class (Always prefer using class over this according to me).

You can check for closure function with the help of __closure__ attribute. This returns a tuple of cell objects if it is a closure function otherwise prints nothing as shown below

In the next blog, we will learn decorators that use closures as well. Hope you enjoy reading.

If you have any doubt/suggestion please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.

Leave a Reply