Python - Factory Functions: Closures

Introduction

Factory functions (a.k.a. closures) create and return functions.

Demo

def maker(N): 
    def action(X):       # Make and return action 
        return X ** N    # action retains N from enclosing scope 
    return action 

f = maker(2)             # Pass 2 to argument N 
print( f ) 
print( f(3) )            # Pass 3 to X, N remembers 2: 3 ** 2 
print( f(4) )            # 4 ** 2 
# from  ww w.ja  va2s.c  o m
#We get the argument cubed when calling the new function, 
#but the original still squares as before: 

g = maker(3)           # g remembers 3, f remembers 2 
print( g(4) )          # 4 ** 3 
print( f(4) )          # 4 ** 2

Result

A lambda would serve in place of a def:

Demo

def maker(N): 
    return lambda X: X ** N           # lambda functions retain state too 
#  w  w w. j a  va2s . c  o m
h = maker(3) 
print( h(4) )                                  # 4 ** 3 again

Result