Python Closures

Definition
The technique by which some data gets attached to the code is called closure in Python.
The value in the enclosing scope is remembered even when the variable goes out of scope or the function itself is removed from the current namespace.

The criteria that must be met to create closure in Python are summarized in the following points.
  1. We must have a nested function (function inside a function).
  2. The nested function must refer to a value defined in the enclosing function.
  3. The enclosing function must return the nested function.
def print_msg(msg):
    def printer():
        print(msg)
    return printer

another = print_msg("Hello")
>>> another()
Hello
>>> del print_msg
>>> another()
Hello
>>> print_msg("Hello")
Traceback (most recent call last):
...
NameError: name 'print_msg' is not defined


Use Cases
1. Closures can avoid the use of global values and provides some form of data hiding.
2. When there are few methods (one method in most cases) to be implemented in a class, closures can provide an alternate and more elegant solutions. But when the number of attributes and methods get larger, better implement a class.

def make_multiplier_of(n):
    def multiplier(x):
        return x * n
    return multiplier

# Multiplier of 3
times3 = make_multiplier_of(3)

# Multiplier of 5
times5 = make_multiplier_of(5)

# Output: 27
print(times3(9))

# Output: 15
print(times5(3))

# Output: 30
print(times5(times3(2)))


3. Decorators in Python make an extensive use of closures.

def smart_divide(func):
   def inner(a,b):
      print("I am going to divide",a,"and",b)
      if b == 0:
         print("Whoops! cannot divide")
         return
      return func(a,b)
   return inner
@smart_divide
def divide(a,b):
    return a/b


>>> divide(2,5)
I am going to divide 2 and 5
0.4
>>> divide(2,0)
I am going to divide 2 and 0
Whoops! cannot divide


Courtesy
https://www.programiz.com

Comments

Popular posts from this blog

Python Decorators

Python Higher Order Functions