Define closure:

Closure is a higher order function that encapsulate one or several other functions. The enclosed functions have access to variables used when the function was created. In python enclosed variables are read only. However there is a workaround to help resolve this issue. We use a dictionary or a list as local variable. The elements enclosed into a container can be read and write

# Create a closure with mutable attribute: index
def test_closure(max):
    index = {1:-1}
    def enclosed():
        if index[1] <= max:
           index[1] += 1
           return index[1]
        else:
           return -1
    return enclosed

def main():
    # use closure based function my_scan()
    my_scan = test_closure(5);
    for i in range(0,5):
        print(i,'->',my_scan())


# compiler entry point
if __name__ == "__main__":
    main()

Using Closure

We use closure like a small class to create function instances. This is the secret, we encapsulate one or several states with the new function. This is helping to create similar functions at runtime based on different parameter values. Closures can help to avoid using Global variables.

test_closure(max)

In the example above function test_closure is a closure function because it returns a function enclosed. This function is captured using closure invocation: my_scan = test_closure(5);

my_scan()

Function my_scan is a function instance because it was created out of enclosure at runtime. Once instantiated my_scan function can be used like any other function. It is like a generator. Returns next number each time is called up to 5 then will return -1.

0 -> 0
1 -> 1
2 -> 2
3 -> 3
4 -> 4

Read next: Generator