The easiest way is to write a separate function to create the lambda.
def mkfun(foo, x):
f = lambda x=x, *y: foo(x, y, f)
return f
for ...:
...mkfun(foo, x)...
This works just like gnibbler's suggestion but can be used in a for loop.
EDIT: I wasn't joking. It really works!
def foo(x, y, bar):
print x
if y:
bar() # call the lambda. it should just print x again.
# --- gnibbler's answer
funs = []
for x in range(5):
bar=lambda x=x, *y: foo(x, y, bar) # What does bar refer to?
funs.append(bar)
funs[2](2, True) # prints 2 4 -- oops! Where did the 4 come from?
# --- this answer
def mkfun(x, foo):
bar = lambda x=x, *y: foo(x, y, bar) # different bar variable each time
return bar
funs = []
for x in range(5):
funs.append(mkfun(x, foo))
funs[2](2, True) # prints 2 2