[Python-ideas] for/else syntax

Carl Johnson cmjohnson.mailinglist at gmail.com
Sat Oct 3 03:30:06 CEST 2009


Stephen J. Turnbull:

> [1]  StopIteration can, but I thought raising StopIteration in user
> code is considered quite bad form.

No, StopIteration doesn't get caught unless it happen in the loop's
get the next iter item phase:

>>> def stop(): raise StopIteration
...
>>> def yields_one():
...     yield 1
...     stop()
...     yield 2
...
>>> def yields_two():
...     yield 1
...     yield 2
...     stop()
...
>>> for i in yields_one(): #catches the stop
...     print(i)
...
1
>>> for i in yields_two(): #catches
...     print(i)
...
1
2
>>> for i in yields_two():
...     print(i)
...     stop() #goes through
…
1
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "<stdin>", line 1, in stop
StopIteration
>>>

— Carl



More information about the Python-ideas mailing list