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?
You are basically creating a closure.
Related reading: Closures: why are they so useful?
From http://docs.python.org/reference/compound_stmts.html:
People answered correctly about the closure, that is: the valid value for "n" inside action is the last value it had whenever "maker" was called.
One ease way to overcome this is to make your freevar (n) a variable inside the "action" function, which receives a copy of "n" in the moment it is run:
The easiest way to do this is to set "n" as a parameter whose default value is "n" at the moment of creation. This value for "n" stays fixed because default parameters for a function are stored in a tuple which is an attribute of the function itself (action.func_defaults in this case):
Usage:
You are defining TWO functions. When you call
you're defining a function that returns twice the number, so
Then, you define ANOTHER DIFFERENT FUNCTION
that return three times the number
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)