Python – Closure
Till now we have observed functions, decorators, Nested Decorators, Nested Functions. To understand why we need Closure let us see in detail about Nested Functions as Closures play a major role when we have Nested Functions.
The problem we do face is whenever we have nested functions which ideally means a function has many child functions internally due to which internal logic may be exposed and memory will be utilized for all the functions when the main function is called even though all child functions are not being used.
Also, we have a kind of variable called Local and Non Local Variables which are ideally referred to as Global variables.
Let us understand this through an example below:
def print_text (text): # This is the outer enclosing function def printer(): # This is the nested function print(text) printer() # We execute the function # Output: Hello print_text("Hello")
Here we can clearly observe that text which has been defined as a part of outer enclosing function print_text is being accessed by printer() function which is the nested function.
Suppose if we have accidentally returned printer function without calling printer() method as below then memory would be used in a huge manner.
Let us see the code example as:
def print_text (text): # This is the outer enclosing function def printer(): # This is the nested function print(text) return printer # We execute the function # Output: Hello calling = print_text("Hello") calling()
Here we have been calling Hello through calling function. The tightly couple behaviour between message and calling() function is referred to as Closure in Python.
Usually Decorators make extensive use of Closures in Python.