How does GC affect generator context managers?

Duncan Booth duncan.booth at invalid.invalid
Tue Nov 30 10:01:15 EST 2010


Jason <jason.heeris at gmail.com> 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 
collected.

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

...

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

   


-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list