Before seeing what closure is, we must first understand what nested functions and non-local variables are.
Nested functions in Python
A function that is defined inside another function is called a nested function. Nested functions can access environment variables.
In Python, these non-local variables can only be accessed within their scope, not outside of it. This can be illustrated with the following example:
As we can see, innerFunction () can be easily accessed inside the body of externalFunction, but not outside its body. Hence, here, innerFunction () is treated as a nested function that uses text as a non-local variable.
Closing — it is a functional object that remembers the values in nested scopes, even if they are not in memory.
- This is the entry that stores the function along with the environment: a mapping that binds each free function variable (variables that are used locally, but defined in a nested scope) with the value or reference to which the name was bound when closing was created.
- Closure — as opposed to the simple function — allows functions to access these captured variables through copies of their values or closure references, even if the function is called outside of their scope.
Output: omkarpathak @ omkarpathak-Inspiron-3542: ~ / Documents / Python-Programs / $ python Closures.py Hey!
- As you can see from the above code, closures help to call functions outside of their scope.
- The innerFunction function is only scoped inside an externalFunction. But with closures, we can easily extend its scope to call a function outside of its scope.
< code class = "undefined spaces">
OUTPUT: omkarpathak @ omkarpathak-Inspiron- 3542: ~ / Documents / Python-Programs / $ python MoreOnClosures.py 6 9 5 10
When and why to use closures:
- Since closures are used as callback functions, they provide a kind of data hiding. This helps us reduce the use of globals.
- When there are few functions in our code, closures are efficient. But if we need to have a lot of features, then let’s go to the (OOP) class.
This article is provided by Omkar Pathak . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting the article [email protected] ... See my article appearing on the Python.Engineering homepage and help other geeks.
Please post comments if you find anything wrong or if you’d like to share more information on the topic discussed above.