I have a situation like the following:
functions = []
some_list = [('a', 'b'), ('c', 'd')]
for x, y in some_list:
def foo(z):
# do some things
return "{} {} {}".format(x, y, z)
functions.append(foo)
But obviously this doesn't work, as x
and y
will always have the last values they had in the loop, i.e. 'c' and 'd', i.e. both functions in the functions
list will return '{} c d'.format(z)
in practice.
How do I make it so that it does the string substitution immediately, so that on the first loop it defines foo(z) as the equivalent to
def foo(z):
# do some things
return "{} a b".format(z)
without any reference to the variables x
and y
?
EDIT: I now realize I also need to store a copy of foo
in functions
, not foo
itself, but the rest of the question stll stands.