Functions in functions

In Python, we can define functions in functions.

Variables are bounded by reference.

def f():
    i = 1
    def g():
        return i+1
    i = 2
    return g()

f()
3

Do not worry. For bounding by value it is sufficient to just pass the value as a default parameter. So we can also do the bounded by value.

def f():
    i = 1
    def g(x,i=i):
        return i+x
    i = 2
    return g(20)

f()
21
def f():
    A = []
    for i in range(10):
        def g(i=i):
            return i+1
        A.append(g)
    return A

f()[5]()
6

The same ideas work for lambda expressions.

def f():
    return [lambda : i+1 for i in range(10)]

f()[5]()
10
def f():
    return [lambda i=i: i+1 for i in range(10)]

f()[5]()
6