How does one capture a value (as opposed to a reference) in a python closure?
What I have tried:
Here is a function which makes a list of parameter-less functions, each of which spits out a string:
def makeListOfFuncs( strings):
list = []
for str in strings:
def echo():
return str
list.append( echo)
return list
If closures in python worked like every other language, I would expect that a call like this:
for animalFunc in makeListOfFuncs( ['bird', 'fish', 'zebra']):
print( animalFunc())
... would yield output like this:
bird
fish
zebra
But in python instead, we get:
zebra
zebra
zebra
Apparently what is happening is that the closure for the echo function is capturing the reference to str, as opposed to the value in the call frame at the time of closure construction.
How can I define makeListOfFuncs, so that I get 'bird', 'fish', 'zebra'?
