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?
To work around the late binding issue, you can use default keyword parameter: