[prev in list] [next in list] [prev in thread] [next in thread] 

List:       python-list
Subject:    Re: How does GC affect generator context managers?
From:       Duncan Booth <duncan.booth () invalid ! invalid>
Date:       2010-11-30 15:01:15
Message-ID: Xns9E4098C722A2Dduncanbooth () 127 ! 0 ! 0 ! 1
[Download RAW message or body]

Jason <jason.heeris@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
[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic