Settled on an extra argument to __next__() and next() to distinguish

between values and exceptions.
This commit is contained in:
Guido van Rossum 2005-04-27 22:41:48 +00:00
parent e18916a7b6
commit c3ff8b06c7
1 changed files with 25 additions and 11 deletions

View File

@ -287,29 +287,42 @@ Specification: Alternative __next__() and Generator Exception Handling
The above specification doesn't let the generator handle general
exceptions. If we want that, we could modify the __next__() API
to take either a value or an exception argument. When it is an
Exception instance, it is raised at the point of the resuming
yield; otherwise it is returned from the yield-expression (or
ignored by a yield-statement). Wrapping a regular value in a
ContinueIteration is then no longer necessary. The translation of
a block-statement would become:
to take either a value or an exception argument, with an
additional flag argument to distinguish between the two. When the
second argument is True, the first must be an Exception instance,
which raised at the point of the resuming yield; otherwise the
first argument is the value that is returned from the
yield-expression (or ignored by a yield-statement). Wrapping a
regular value in a ContinueIteration is then no longer necessary.
The next() built-in would be modified likewise:
def next(itr, arg=None, exc=False):
nxt = getattr(itr, "__next__", None)
if nxt is not None:
return nxt(arg, exc)
if arg is None and not exc:
return itr.next()
raise TypeError("next() with args for old-style iterator")
The translation of a block-statement would become:
itr = EXPR1
arg = val = None
ret = False
ret = exc = False
while True:
try:
VAR1 = next(itr, arg)
VAR1 = next(itr, arg, exc)
except StopIteration:
if ret:
return val
break
try:
arg = val = None
ret = False
ret = exc = False
BLOCK1
except Exception, arg:
pass
exc = True
The translation of "continue EXPR2" would become:
@ -319,6 +332,7 @@ Specification: Alternative __next__() and Generator Exception Handling
The translation of "break" inside a block-statement would become:
arg = StopIteration()
exc = True
continue
The translation of "return EXPR3" inside a block-statement would
@ -326,7 +340,7 @@ Specification: Alternative __next__() and Generator Exception Handling
val = EXPR3
arg = StopIteration()
ret = True
ret = exc = True
continue
The translation of a for-loop would be the same as indicated