[Python-ideas] Propagating StopIteration value

Guido van Rossum guido at python.org
Sun Oct 7 03:45:54 CEST 2012

On Sat, Oct 6, 2012 at 6:09 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> A concrete example would be useful for those who don't know about the (new?)
> StopIteration.value attribute. I think you are referring to this:
> py> def myiter():
> ...     yield 1
> ...     raise StopIteration("spam")
> ...
> py> it = map(lambda x:x, myiter())
> py> next(it)
> 1
> py> next(it)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> StopIteration
> The argument given to StopIteration is eaten by map.
> But this is not *new* to 3.3, it goes back to at least 2.4, so I'm
> not sure if you are talking about this or something different.

What's new in 3.3 (due to PEP 380) is that instead of the rather
awkward and uncommon

  raise StopIteration("spam")

you can now write

  return "spam"

with exactly the same effect.

But yes, this was all considered and accepted when PEP 380 was debated
(endlessly :-), and I see no reason to change anything about this.
"Don't do that" is the best I can say about it -- there are a zillion
other situations in Python where that's the only sensible motto.

--Guido van Rossum (python.org/~guido)

More information about the Python-ideas mailing list