First Class functions in Python

  • In Python when functions treated like any other variable then they are term as First-class functions
  • Properties of first class functions:
    • Assign to a variable.
    • Pass the function as a parameter to another function.
    • Return a function from another function.
def one(msg):
    print(msg)
one("Hello!")

two = one
two("Hello!")

Functions are objects –> assigning function to a variable.

def shout(text):
    return text.upper()
print(shout('Hello'))

# assigned to var
yell = shout
print(yell('Hello'))

Functions can be passed as arguments to other functions

def shout(text):
    return text.upper()

def whisper(text):
    return text.lower()

def greet(func):
    greeting = func("Hi, function ")
    print(greeting)

# passed as arguments
greet(shout)
# HI, FUNCTION
greet(whisper)
# hi, function 

Functions can return another function

def adder1(x):
    print("adder1" + x )
    return adder2

def adder2(y):
    print("added2" + y)

adder = adder1('One')
print(adder)
adder('two')

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