[Python-ideas] Revised**7 PEP on Yield-From

Nick Coghlan ncoghlan at gmail.com
Sun Mar 22 00:22:00 CET 2009

Greg Ewing wrote:
> Jacob Holm wrote:
>>     # This causes a StopIteration in iterator.next().  After grabbing
>>     # the value in the "except StopIteration" clause of the PEP
>>     # expansion, the "finally" clause calls iterator.close().
> Okay, I see what you mean now. That's a bug in the expansion.
> Once an iterator has raised StopIteration, it has presumably
> already finalized itself, so calling its close() method
> shouldn't be necessary, and I hadn't intended that it should
> be called in that case.

close() *should* still be called in that case - the current expansion in
the PEP is correct. It is the *iterator's* job to make sure that
multiple calls to close() (or calling close() on a finished iterator)
don't cause problems. The syntax shouldn't be trying to second guess
whether or not calling close() is necessary or not - it should just be
calling it, period.

>>> def gen():
...   yield 1
>>> g = gen()
>>> g.next()
>>> g.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
>>> g.close()
>>> g.close()
>>> g2 = gen()
>>> g.close()
>>> g.close()
>>> g3 = gen()
>>> g3.next()
>>> g.close()
>>> g.close()


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list