Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #3832

Closing generators

From Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de>
Newsgroups comp.lang.python
Subject Closing generators
Date 2011-04-22 03:14 +0200
Organization A newly installed InterNetNews server
Message-ID <ioqkpc$qco$1@r03.glglgl.eu> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextNext in thread | Find similar


Thread

Closing generators Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2011-04-22 03:14 +0200
  Re: Closing generators Terry Reedy <tjreedy@udel.edu> - 2011-04-21 23:59 -0400
  Re: Closing generators Wolfgang Rohdewald <wolfgang@rohdewald.de> - 2011-04-22 09:01 +0200
    Re: Closing generators Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2011-04-22 10:01 +0200
      Re: Closing generators Terry Reedy <tjreedy@udel.edu> - 2011-04-22 22:15 -0400
        Re: Closing generators Thomas Rachel <nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915@spamschutz.glglgl.de> - 2011-04-24 05:18 +0200

csiph-web