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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With