iterators: class vs generator

Andrew Durdin adurdin at gmail.com
Wed Aug 25 14:19:40 CEST 2004


On Wed, 25 Aug 2004 11:24:41 GMT, Michael Hudson <mwh at python.net> wrote:
> 
> Here's a better illustration:
> 
> >>> def iterable_via_generator():
> ....     yield "one"
> ....     raise Exception()
> ....     yield "two"
> ....
> >>> i = iterable_via_generator()
> >>> i.next()
> 'one'
> >>> i.next()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   File "<stdin>", line 3, in iterable_via_generator
> Exception
> >>> i.next()
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> StopIteration


This is correct behaviour according to PEP 255:
"""
If an unhandled exception-- including, but not limited to,
StopIteration --is raised by, or passes through, a generator function,
then the exception is passed on to the caller in the usual way, and
subsequent attempts to resume the generator function raise
StopIteration.  In other words, an unhandled exception terminates a
generator's useful life.
"""



More information about the Python-list mailing list