Closing generators

Terry Reedy tjreedy at
Fri Apr 22 05:59:15 CEST 2011

On 4/21/2011 9:14 PM, Thomas Rachel wrote:
> 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.

That is very rarely necessary. generator.close was added so that one 
could tell the generator to close anything opened within the generator, 
such as a file, that needs to be explicitly closed.

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

When returning from the function, g, if local, should disappear.

Terry Jan Reedy

More information about the Python-list mailing list