Closing generators

Thomas Rachel nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Fri Apr 22 03:14:15 CEST 2011


Hi folks,

it is possible to close a generator. That is (among others) for the 
following case:

I run a for loop over the iterator, but then I break it. Now I can leave 
the generator to the GC (which is AFAI have been told a thing which I 
should not do), or I can clean up myself.

Example:

for i in g:
   if i is not None:
     g.close()
     return i

or better

try:
   for i in g:
     if i is not None:
       return i
finally:
   g.close()

or even better

with contextlib.closing(g):
   for i in g:
     if i is not None:
       return i

How do you do that in this case - do you just drop the generator, or do 
you close it? (Beware of exceptions which could happen!) Till now, I 
used to just drop it, but now I am thinking about if it is good style or 
not...

Another question: AFAICT generator.close() was introduced at about the 
same time as the with statement. Was a matching context manager 
deliberately left away, or just forgotten? It is fine to work with 
"with" on a file or other closable object - why not on a generator, 
without contextlib.closing()?


TIA,

Thomas



More information about the Python-list mailing list