Closures in Python
Python supports anonymous functions, which are also known as lambda functions. These can form closures. Anonymous functions are useful when you want to define a function inline without having to name it.
This Python code demonstrates the concept of closures. The int_seq
function returns another function, which we define inside the body of int_seq
. The returned function closes over the variable i
to form a closure.
To run the program:
In Python, we use the nonlocal
keyword to indicate that a variable should be accessed from an enclosing scope, not including the global scope. This is similar to how the closure in the original example captures and modifies the i
variable.
The last feature of functions we’ll look at for now is recursion, which is also supported in Python.