Also remember, everything in Python is an object.
LEGB Rule in Python
When you reference a variable, Python will for it in the following order:-
- First in the local scope
- Second in any enclosing function's local scope
- Thirdly in the global scope
- and finally, the built-in scope.
The first occurrence of the variable wins.
Defining a Closure Function
Let’s look at an example.
def numbers(): x = 100 def print_it(): print(x) print_it() numbers()
In the example above, what would you expect if the last line of the function
numbers() returned the
print_it() function instead of calling it? This means the function would be defined as follows.
def numbers(): x = 100 def print_it(): print(x) return print_it result = numbers() result()
What actually happened there?
Explanation of Python Closures
numbers() function was called inside which a variable
x has been defined. The returned function is assigned to the variable
result. On calling
result(), the value of variable
x was still remembered although we had already finished executing the
This way of being able to remember the variable in an enclosing scope of the
print_it() function, even though it is still not active, is called Closure in Python.
Python Closures are nested function referencing a value in their enclosing scope.
Criteria for using Python Closures
- There must be a nested function.
- The nested function must refer to a variable defined in the enclosing function.
- The enclosing function must return the nested function.
Advantages of using Closures in Python
- Avoid the use of global variables.
- Allows data hiding.
- Also provides an object-oriented solution.
You will understand Python Closures, using this video. So, do watch it!