Repository navigation
Let StopIteration be caught in try/except - #920
Conversation
b8c3717 to
c89c40b
Compare
|
Thanks @HoneyBearTech, this is thorough, and catching Python already keeps the original exception: the converted The rest are mostly |
c89c40b to
0470f71
Compare
Python turns a StopIteration that leaves a coroutine into
RuntimeError("coroutine raised StopIteration"), so next() on an empty
iterator, a native __next__ or a raise StopIteration in a script could
never be caught with except StopIteration.
Python keeps the original StopIteration as that RuntimeError's
__cause__, and the RuntimeError passes unchanged through the
interpreter's other coroutines. A small helper recovers the
StopIteration from it, and it's used only where a script sees the
exception: try/except matches and binds it, with passes it to
__exit__/__aexit__, and the uncaught error report and Jupyter's error
reply show it, with the script's lines. The report also stops at an
exception chain that loops back, which raise exc in
except StopIteration as exc can create. An element, condition or inner
iterable of a generator expression that raises it gives
RuntimeError("generator raised StopIteration"), as in Python. The
exceptions themselves aren't changed, and one that isn't caught carries
on as before.
The differences that remain are listed in the language limitations in
the docs.
Tests compare the results with CPython, and check what pyscript does
where it differs.
Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com>
|
Thanks @craigbarratt, that's a much better approach. I've rebuilt the PR from scratch on current master that way, as one new commit. Size and the rule for future code. The private The four places you listed:
The scripts (numbered as in the first version's list). 44 of the 57 still match CPython and stay as comparison scripts. That's your 41 plus 17, 38 and 47, which are the generator expression ones: your trial didn't have the
What I added beyond the four places, and why:
It merges cleanly into master. With #919, |
0470f71 to
8d5b6b0
Compare
craigbarratt
left a comment
There was a problem hiding this comment.
Thanks @HoneyBearTech, this is a big improvement: much smaller, and with no rule for future code. Good catch on the chain cycle in the report. Approving.
What was broken
A
StopIterationcould never be caught in pyscript, even in the simplest script:An uncaught one was reported as
RuntimeError: coroutine raised StopIteration, which doesn't say what really happened. And in a generator expression, an element that raised it didn't give Python'sRuntimeError("generator raised StopIteration").Why
AstEval(aeval()and theast_*methods).StopIterationthat leaves a coroutine intoRuntimeError("coroutine raised StopIteration").StopIterationfromnext(), an iterator's__next__, any native function, or a script's ownraise StopIterationleft the coroutine it was raised in as aRuntimeError.except StopIterationnever matched, andwithblocks passed theRuntimeErrorto__exit__.RuntimeErrorhas theStopIterationas its__cause__, and it passes unchanged through pyscript's outer coroutines, because Python only replaces aStopIteration.What I changed
This is a rework of the first version of this PR, following @craigbarratt's suggestion: instead of catching the
StopIterationeverywhere pyscript's coroutines meet it, it is recovered from theRuntimeErroronly where a script can see the exception. The private carrier exception and the catches spread through the interpreter are gone, so no future coroutine has to follow a special rule.unwrap_stop_iteration(). It recognises Python's replacement: an exception whose type is exactlyRuntimeError, whose only argument is the string"coroutine raised StopIteration", and whose__cause__is aStopIteration. It returns thatStopIteration. Any other exception comes back unchanged. It checks the argument's type before comparing it, so an argument with its own__eq__is never called. The exception objects themselves are never changed.exceptclauses (ast_try). Each clause is matched against the recovered exception, and that's what theasname is bound to. Soexcept StopIteration, tuple handlers,except Exception as exc,except BaseException as exc, a subclass ofStopIteration,.valueand.argswork as in Python, andexcept RuntimeErrordoesn't catch it. If no clause matches, the original error carries on unchanged. The interpreter's outer catches stay as they are, so cancelling a task works as before.with(with_items).__exit__and__aexit__get the recovered exception's type, value and traceback. Socontextlib.suppress(StopIteration),@contextlib.contextmanagerandnullcontext()work. If__exit__doesn't suppress it, the original error carries on. Cancelling still works as before.EvalExceptionFormatter, used for the log,task.create()errors and Jupyter). It shows theStopIterationwith the script's own lines and function names. Python keeps those lines on theRuntimeError's traceback, not on theStopIteration, so the report reads the replacement's traceback first and then theStopIteration's own (which has the frames of a native function that raised it). It also stops when an exception chain loops back to an exception it has already shown.raise excinsideexcept StopIteration as excmakes such a loop, and without this the report itself failed withRecursionError. Forraise ValueError() from exc, the report looks along the context chain for theRuntimeErrorthat replacedexc, so the cause is shown with the line that raised it, even when another exception was handled in between. That search is cycle-safe too.genexp_loop). AStopIterationfrom an element, anifcondition or an inner iterable is raised again from the generator, so Python itself givesRuntimeError("generator raised StopIteration"), with theStopIterationas both its__cause__and__context__, as in Python. It is raised with a traceback that puts theRuntimeError's script frames in front of its own, so the report still shows the function that raised it and its line. The traceback is made of new traceback objects, so theRuntimeErrorisn't changed. The traceback is read and set throughBaseException's own descriptor and method, as Python does internally, so a subclass's__traceback__orwith_traceback()override is never called.withpasses__exit__the traceback the same way. Before, it surfaced asRuntimeError("coroutine raised StopIteration"). The normal end of the loop and the outermost iterable work as before.jupyter_kernel.py). The kernel already used the same report for the traceback, but took the error's name and message straight from the caught error. It now takes them from the exception the report shows, soenameandevaluesayStopIterationand its value in both theexecute_replyand the publishederrormessage."coroutine raised StopIteration", not"async generator raised StopIteration". pyscript has no async generators of its own, so that message only ever comes from native code, where Python'sRuntimeErroris genuine and stays one.eval.pygets 67 new lines and loses 17. 50 of the new lines are code, and the rest are comments, a docstring and blank lines.jupyter_kernel.pygets 4 new lines and loses 3. The first version's own commit added 648 lines toeval.pyand removed 424.Testing
test_stop_iteration_matches_pythonintests/test_unit_eval.py. It runs 49 scripts in CPython and in pyscript and compares every result:next()with and without a default;raise StopIteration,StopIteration(5)and several arguments;except StopIteration, tuple handlers,except Exception as exc,.valueand.args; a bareraiseandraise excin a handler,raise ... from, handlers that clear the traceback, andfinally;withandasync withwhose__exit__/__aexit__sees and suppresses it,contextlib.suppress,@contextlib.contextmanagerandnullcontext(); a function that raises it to its caller; native callbacks (asortedkey,functools.partial, a property,map);forloops, comprehensions and generator expressions, including an element, a condition and an inner iterable that raise it; native special methods (+,==,not, unary-,in,__setitem__, a property setter,__iter__,__hash__); properties, setters, deleters,__setattr__/__delattr__and classmethods from Support @property and @classmethod on pyscript class methods #918, including aStopIterationsubclass;__prepare__,eval(),exec()and decorators;__init__,super().__init__(),Base.__init__()and__new__; and aRuntimeErrorwhose argument has an__eq__that must never be called.except BaseException as exc, a bareexcept:, a subclass, andexcept RuntimeErrornot catching it;RuntimeErrorwith Python's message but no cause or another cause, and one with the async generator message and aStopIterationcause, all of which stayRuntimeError;__exit__that raisesStopIterationitself, or returns an object whose truth test raises it;StopIterationsubclass that overrideswith_traceback()and__traceback__, in a generator expression and in awithblock. Python uses neither override when it converts or passes on the exception, and neither does pyscript.test_stop_iteration_limitschecks what pyscript actually does in the cases that differ from Python (see Docs), so a later change can't alter them without a test noticing. It covers the cases behind the 13 scripts of the first version that no longer match Python, plus a pyscriptasync defthat raises it and native code that awaits a pyscript function that raises it.test_stop_iteration_uncaught_reportchecks the error report:StopIterationwith the script line, and withoutRuntimeError: a plainnext(), a function that raises it, a bareraise,raise excat top level,raise exctwice in nested handlers in a function (both make a loop in the exception chain), and a native function, whose own frame is shown too;StopIterationas its context, andraise ValueError() from excshows it as its cause, with the line that raised it, also when another exception was handled in between;raise ValueError() from savedafter the handler has finished shows the cause without its script line (the documented limit);StopIteration, with the function that raised it and its line, as the direct cause ofRuntimeError: generator raised StopIteration;task.create()logs is reported asStopIterationwith the function's line.test_jupyter_kernel_msgschecks thatraise StopIteration(5)gives the error nameStopIteration, the value5and a traceback ending with the script line andStopIteration: 5, in both theexecute_replyand the publishederrormessage.except,withand generator expressions. The other 6 pass there too, because they check behaviour pyscript already had: the two scripts whoseRuntimeErrorargument has an__eq__, the native callback inmap(), the cause and context of a generator expression's error, aRuntimeErrorwith Python's message but noStopIterationcause, and the native generators' errors.sphinx-build -Wpass on Python 3.14.Docs
A new item in Language Limitations says that
StopIterationcan be caught withexceptand suppressed by awithstatement, that an uncaught one is reported asStopIteration, and that a generator expression element givesRuntimeError("generator raised StopIteration"), all as in Python. It then lists what still differs:exceptclause's type, its handler and afinallyblock,sys.exception(),sys.exc_info()and the__context__of a new exception are Python'sRuntimeError("coroutine raised StopIteration"), not theStopIteration. A bareraiseandraise excstill raise theStopIteration;RuntimeErrorbecause aStopIterationleft a native coroutine (also in a task) or a pyscriptasync def,exceptsees theStopIterationinstead. The same goes for aRuntimeErrorwith that message that a script raisesfromaStopIteration;StopIterationgets thatRuntimeError;fromaStopIterationafter the handler that caught it has finished is reported without theStopIteration's script lines.Note
Remaining differences from Python that this PR doesn't fix:
except*(exception groups) isn't supported in pyscript, as before;except BaseExceptiononly catchesExceptionsubclasses in pyscript, as before.This PR is now one commit on current master, which includes the lambda PR (#919). It merges into master with no conflicts. Both PRs add tests at the end of tests/test_unit_eval.py, and this commit keeps #919's tests and adds its own after them.