def list_files():
for fn in ["example.txt", "data.txt"]:
yield fn, lambda: "sample contents of %s" % fn
for fn, body in list(list_files()):
if fn.endswith('.txt'):
print body()
print "---"
# fixed version:
def list_files():
for fn in ["example.txt", "data.txt"]:
# "captures" fn for each lambda
yield fn, lambda fn=fn: "sample contents of %s" % fn
for fn, body in list(list_files()):
if fn.endswith('.txt'):
print body()