How do nested functions work in Python? How do nested functions work in Python? python python

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.


You can see it as all the variables originating in the parent function being replaced by their actual value inside the child function. This way, there is no need to keep track of the scope of the parent function to make the child function run correctly.

See it as "dynamically creating a function".

def maker(n):  def action(x):    return x ** n  return actionf = maker(2)--> def action(x):-->   return x ** 2

This is basic behavior in python, it does the same with multiple assignments.

a = 1b = 2a, b = b, a

Python reads this as

a, b = 2, 1

It basically inserts the values before doing anything with them.


You are defining TWO functions. When you call

f = maker(2)

you're defining a function that returns twice the number, so

f(2) --> 4f(3) --> 6

Then, you define ANOTHER DIFFERENT FUNCTION

g = maker(3)

that return three times the number

g(3) ---> 9

But they are TWO different functions, it's not the same function referenced, each one it's a independent one. Even in the scope inside the function 'maker' are called the same, is't not the same function, each time you call maker() you're defining a different function. It's like a local variable, each time you call the function takes the same name, but can contain different values. In this case, the variable 'action' contains a function (which can be different)