For understanding closures, first we need to understand nested functions and non-local variables in python that are there for data science.
A function defined inside another function is known as a nested function. These functions can access variables of the enclosing scope.
In case of Python non-local variables can be accessed only within their scope and not outside it. It will be clear with an example:
From the above example, we can say that innerFunction() is treated as a nested function and it uses text as a non-local variable.
Closures are function objects which remember the values in enclosing scopes even if they are not present in memory.
- It acts as a record for storing a function along with an environment. It is a mapping associated with each free variable of the function with the value of reference to which name was bound while the creation of closure took place.
- A closure allows a function to gain access to captured variables by the closure’s copies of values or reference. It will take place even when the function invoked is outside the scope.
It is clear from the above example that the function innerFunction had its scope only inside the outerFunction. But when closures came into the picture we were able to invoke a function outside its scope.
When and Why Closures should be used?
- Closures being a call back function provide data hiding of some sort. It, in turn, helps in reducing the use of global variables.
- Closures are efficient when we are dealing in codes with few functions.