This PEP proposes that generators should grow such a close method with such semantics that the example could be rewritten as:
def all_lines(index_path): index = file(index_path,"r") try: for path in file(index_path,"r"): document = file(path.strip(),"r") try: for line in document: yield line finally: document.close() finally: index.close()
all = all_lines("index.txt") try: for line in all: ... finally: all.close()
[snip]
PEP 288 [2] proposes a more general solution, allowing custom exception passing to generators.
Is there any reason to prefer gen.close() over the more general solution gen.throw(Close) which results in nearly identical code and yet allows other exception types to be handled as well? Note, the general purpose solution is a natural extension of the existing syntax and is easily implemented without messing with 'try/finally'. Pretty much all that was holding up the general solution was that I had not convinced Guido that the clean-up problem exists in practice. It looks like you've surmounted that obstacle for me. Raymond Hettinger