[Python-Dev] pre-PEP: Resource-Release Support for Generators

Raymond Hettinger python at rcn.com
Tue Aug 26 17:17:41 EDT 2003

 >      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()
>      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

More information about the Python-Dev mailing list