How does GC affect generator context managers?

Duncan Booth duncan.booth at invalid.invalid
Tue Nov 30 16:01:15 CET 2010

Jason <jason.heeris at> wrote:

> As I understood it, when the "with" block exits, the __exit__() method
> is called immediately. This calls the next() method on the underlying
> generator, which forces it to run to completion (and raise a
> StopIteration), which includes the finally clause... right?
That is true if the "with" block exits, but if the "with" block (or 
"try".."finally" block) contains "yield" you have a generator. In that case 
if you simply drop the generator on the floor the cleanup at the end of the 
"with" will still happen, but maybe not until the generator is garbage 

def foo():
   with open("foo") as foo:
      for line in foo:
          yield line


bar = foo()
del bar # May close the file now or maybe later...


Duncan Booth

More information about the Python-list mailing list