How do nested functions work in Python?

eozzy picture eozzy · Jan 5, 2010 · Viewed 59k times · Source
def maker(n):
    def action(x):
        return x ** n
    return action

f = maker(2)
print(f)
print(f(3))
print(f(4))

g = maker(3)
print(g(3))

print(f(3)) # still remembers 2

Why does the nested function remember the first value 2 even though maker() has returned and exited by the time action() is called?

Answer

miku picture miku · Jan 5, 2010

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.