A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope.
When it's useful?
We must have a nested function (function inside a function).
The nested function must refer to a value defined in the enclosing function.
The enclosing function must return the nested function.
def print_msg(msg):
# This is the outer enclosing function
def printer():
# This is the nested function
print(msg)
return printer # this got changed
# Now let's try calling this function.
# Output: Hello
another = print_msg("Hello")
another()
Sample Use
def make_multiplier_of(n):
def multiplier(x):
print "x:",x
print "N:",n
return x * n
return multiplier
# Multiplier of 3
times3 = make_multiplier_of(3)
print times3(2)
#Output
#x: 2
#N: 3
#6