Jason <jason.hee...@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
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to