Menu Close

Articles

Python: 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. This is called “context”.

Functional Programming

Are you familiar with functional programming? If not this concept is harder to understand. In Python you can create functions that will produce as a result another function. That technique is one of many other techniques you can apply in Python for doing interesting stuff with functions.

Example:

Next example is a function that create another function called closure.

Note: In python context variables are read only. However there is a workaround to help resolve this issue: You can use a dictionary or a list with a single element. The elements enclosed into any container can be read and write. In the example, index is a mutable attribute. Nice trick isn’t it?

Using Closure

We use closure like a poor man class to generate function instances. This is the secret, we encapsulate one or several states with the closer function. This is helping to create similar functions at runtime based on different parameter values that can hold a state. Closures can help to avoid polluting the global scope with variables that can become hard to track.

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.

Homework: Try to run this example live: python closure

Read next: Generator