Nested function

  • Function defined inside another function –> nested function
  • Nested functions are able to access variables of the enclosing scope.
def print_msg(msg):
  def printer():
    print(msg)
  printer()

print_msg("Hello")
# Output: Hello

Closure function

  • A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.
  • The function innerFunction has its scope only inside the outerFunction.
  • But with the use of closures we can easily extend its scope to invoke a function outside its scope.
# Calling inner fxn  outside the scope
def print_msg(msg):
  def printer():
    print(msg)
  return printer

another = print_msg("Hello")
another()
# Output: Hello

Python program to illustrate nested functions

def outerFunction(text): 
  def innerFunction(): 
    print(text) 
  innerFunction() 

outerFunction('Hey!') 

Python program to illustrate closures

def outerFunction(text): 
  text = text 
  def innerFunction(): 
    print(text) 
  return innerFunction
  # returning function WITHOUT parenthesis 

myFunction = outerFunction('Hey!') 
myFunction() 

Python program to illustrate closures

def logger(func): 
  def log_func(*args): 
    print(func.__name__, args, end='--> ') 
    print(func(*args)) 
  return log_func		 
  # returning function WITHOUT parenthesis

def add(x, y): 
  return x+y 

def sub(x, y): 
  return x-y 

add_logger = logger(add) 
sub_logger = logger(sub) 

add_logger(3, 3) # add (3, 3)--> 6
add_logger(4, 5) # add (4, 5)--> 9

sub_logger(10, 5)  # sub (10, 5)--> 5
sub_logger(20, 10) # sub (20, 10)--> 10

Reference