Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do nested functions work in Python?

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?

like image 610
eozzy Avatar asked Jan 05 '10 12:01

eozzy


People also ask

How does nested function work?

A nested function can access other local functions, variables, constants, types, classes, etc. that are in the same scope, or in any enclosing scope, without explicit parameter passing, which greatly simplifies passing data into and out of the nested function. This is typically allowed for both reading and writing.

Can you have nested functions in Python?

Inner functions, also known as nested functions, are functions that you define inside other functions. In Python, this kind of function has direct access to variables and names defined in the enclosing function.

Is nested functions a good thing?

One disadvantage of declaring a nested function is the fact that it will be created inside function's environment every time you call the parent function. In theory, this could decrease performance if the parent function is called frequently. But, nested functions are very much used in Javascript.

What is an example of a nested function?

Users typically create nested functions as part of a conditional formula. For example, IF(AVERAGE(B2:B10)>100,SUM(C2:G10),0). The AVERAGE and SUM functions are nested within the IF function.


1 Answers

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.

like image 71
miku Avatar answered Oct 23 '22 15:10

miku