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

Samuele Pedroni pedronis at bluewin.ch
Wed Aug 27 00:09:50 EDT 2003

this was written before reading Guido's last comments.

At 16:17 26.08.2003 -0400, Raymond Hettinger wrote:
>  >      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'.

1) I think we want to enable try-finally, because is the typical way to spell
resource release:

f = file(...,"r")
except GeneratorClose:


f = file(...,"r")
fastexit = 0
except GeneratorClose:
   fastexit = 0
if fastexit: return

2) even if we had gen.throw(...), I think it would be better to have 
explicitly gen.close(), it expresses intention better IMO and feels like 
file.close() etc...

3) for the purpose of close, it seems that forced-return vs. throwing an 
exception on generator side, can have more clearly definable semantics, 
although it has some limitations too.

so the question is whether there are use cases for the more general 
gen.throw(...) different from gen.close() purpose, and if we have it 
whether we can layer a gen.close() with the proper semantics on top of it, 
i.e. we should then clearly think about the issues for exceptions-semantics 
for gen.close().

gen.throw is a bigger gun but they don't kill one another


More information about the Python-Dev mailing list