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
1 2 3 4 5 6 7 8 9 10 |
def name(text): # outer enclosing function def print_name(): # nested function print(text) return print_name name_closure = name("Pankaj") name_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
1 2 3 4 |
>>> name_closure.__closure__ (<cell at 0x0000001F8D4FC528: str object at 0x0000001F8D51FEA0>,) >>> name.__closure__ >>> |
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.