Reputation: 2402
Python beginner question. Say you want to dynamically create a function that keeps some state (in the code below an integer i). Then as the function defined is an object, we could use it later on. In the following code, I add the functions to a list, and each call to print(fn(0))
should result in 0 1 2 3 4
, but instead I get 4 4 4 4 4
as if only the latest value of i
is used.
fns = []
for i in range(5):
def fn(x):
return x + i
fns += [fn]
print(fns)
for fn in fns:
print(fn(0))
quit()
Is it possible to accomplish in Python what this code tries to do?
Upvotes: 0
Views: 94
Reputation: 165
A function that retains its own state? I would do it like this:
class func:
# can behave as a function, but can also hold its own value
def __init__(self, value=0):
self.value = value
# this function is the actual 'function' that is called each time
def __call__(self, arg):
self.value += arg
return self.value
fns = []
for i in range(5):
# create new function, and give it a starting value of i
fn = func(i)
fns += [fn]
for fn in fns:
print( fn(0) )
The result is 0 1 2 3 4
Upvotes: 0
Reputation: 369444
To work around the late binding issue, you can use default keyword parameter:
for i in range(5):
def fn(x, i=i): # <-----
return x + i
....
Upvotes: 3