Closures in Python

Learn about Python closure, how to define a closure, and the reasons you should use it.

Closures in Python

Pre-requisite knowledge

1.Python Functions

2. Variable Scope and Namespace

Also remember, everything in Python is an object.

LEGB Rule in Python

LEGB rule in Python

When you reference a variable, Python will for it in the following order:-

  1. First in the local scope
  2. Second in any enclosing function's local scope
  3. Thirdly in the global scope
  4. and finally, the built-in scope.

The first occurrence of the variable wins.

Defining a Closure Function

Let’s look at an example.

Code

def numbers():
    x = 100
    
    def print_it():
        print(x)
    
    print_it()

numbers()

Solution

100

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.

Code

def numbers():
    x = 100

    def print_it():
        print(x)

    return print_it

result = numbers()
result()

Output

100

What actually happened there?

Explanation of Python Closures

The 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 print_it() function.

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

  1. There must be a nested function.
  2. The nested function must refer to a variable defined in the enclosing function.
  3. The enclosing function must return the nested function.

Advantages of using Closures in Python

  1. Avoid the use of global variables.
  2. Allows data hiding.
  3. Also provides an object-oriented solution.

You will understand Python Closures, using this video. So, do watch it!