How do nested functions work in Python?

You are basically creating a closure.

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be “closed over” its free variables.

Related reading: Closures: why are they so useful?

A closure is simply a more convenient way to give a function access to local state.

From http://docs.python.org/reference/compound_stmts.html:

Programmer’s note: Functions are first-class objects. A ‘def’ form executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section Naming and binding for details.

Leave a Comment