[ create a new paste ] login | about

Link: http://codepad.org/poXS7nc2    [ raw code | output | fork | 1 comment ]

RogerPate - Python, pasted on Feb 19:
# 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.func_code.co_varnames
    # the fn hack is "exposed" on the above line, or with help(body)
    print body()

print "---"

# another way, which creates a new closure for each
# and doesn't "expose" the hack (by using another hack, of course :P):
def list_files():
  for fn in ["example.txt", "data.txt"]:
    # "captures" fn for each lambda
    yield fn, (lambda fn=fn: lambda: "sample contents of %s" % fn)()

for fn, body in list(list_files()):
  if fn.endswith('.txt'):
    print body.func_code.co_varnames
    # can also use help(body) to see the difference
    print body()


Output:
1
2
3
4
5
6
7
8
9
('fn',)
sample contents of example.txt
('fn',)
sample contents of data.txt
---
()
sample contents of example.txt
()
sample contents of data.txt


Create a new paste based on this one


Comments:
posted by RogerPate on Feb 19
reply