Menu Close


Python: closure

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

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.


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);


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.

Read next: Generator