Python - Closures



In this chapter, let us discuss the concept of closures in Python. In Python, functions are said to be first order objects. Just like the primary data types, functions can also be used assigned to variables, or passed as arguments.

Nested Functions

You can also have a nested declaration of functions, wherein a function is defined inside the body of another function.

Example

def functionA():
   print ("Outer function")
   def functionB():
      print ("Inner function")
   functionB()

functionA()

It will produce the following output

Outer function
Inner function

In the above example, functionB is defined inside functionA. Inner function is then called from inside the outer function's scope.

If the outer function receives any argument, it can be passed to the inner function.

def functionA(name):
   print ("Outer function")
   def functionB():
      print ("Inner function")
      print ("Hi {}".format(name))
   functionB()
   
functionA("Python")

It will produce the following output −

Outer function
Inner function
Hi Python

What is a Closure?

A closure is a nested function which has access to a variable from an enclosing function that has finished its execution. Such a variable is not bound in the local scope. To use immutable variables (number or string), we have to use the nonlocal keyword.

The main advantage of Python closures is that we can help avoid the using global values and provide some form of data hiding. They are used in Python decorators.

Example

def functionA(name):
   name ="New name"
   def functionB():
      print (name)
   return functionB
   
myfunction = functionA("My name")
myfunction()

It will produce the following output

New name

In the above example, we have a functionA function, which creates and returns another function functionB. The nested functionB function is the closure.

The outer functionA function returns a functionB function and assigns it to the myfunction variable. Even if it has finished its execution. However, the printer closure still has access to the name variable.

nonlocal Keyword

In Python, nonlocal keyword allows a variable outside the local scope to be accessed. This is used in a closure to modify an immutable variable present in the scope of outer variable.

Example

def functionA():
   counter =0
   def functionB():
      nonlocal counter
      counter+=1
      return counter
   return functionB

myfunction = functionA()

retval = myfunction()
print ("Counter:", retval)

retval = myfunction()
print ("Counter:", retval)

retval = myfunction()
print ("Counter:", retval)

It will produce the following output

Counter: 1
Counter: 2
Counter: 3
Advertisements