Generators and exceptions (was Re: Stackless Python and Python 2.x)
Guido van Rossum
guido at python.org
Sun Sep 9 00:58:31 EDT 2001
aahz at panix.com (Aahz Maruch) writes:
> Okay, I've re-read PEP 255, and I'm still not clear on what happens with
> the following code:
>
> def a():
> yield 1
> raise "foo"
> yield 2
> return
>
> def b():
> return a()
>
> g = b()
> g.next()
> g.next()
>
> (If I've messed up the syntax, please feel free to correct it before
> answering; I *think* my intent is clear enough.)
You don't need the "g = b()" part -- "g = a()" has the same effect.
This prints 1 as a result of the first call to g.next(), and raises a
foo exception as a result of the second g.next() call. After that,
any call to g.next() raises StopIteration, because after raising an
exception, the generator's frame is no longer resumable.
IOW, a raise from a generator is passed right through the next()
call, and the generator terminates for good. Ditto for a return: this
is (mostly) equivalent to raising StopIteration.
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-list
mailing list