By Lenin Mishra
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 functionsí local scopes
- Thirdly in the global scope, and finally
- Finally in 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
numbers() returned the
instead of calling it? This means the function would be defined
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
has been defined.
The returned function is assigned to the variable
result(), the value of variable
still remembered although we had already finished executing
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.
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
- Avoid use of global variables.
- Allows data hiding.
- Also provides an object oriented solution.
Build your foundation in Python with our self-paced Python Bootcamp for Beginners.