Skip to content

Let StopIteration be caught in try/except - #920

Merged
craigbarratt merged 1 commit into
custom-components:masterfrom
HoneyBearTech:fix-stopiteration
Nov 22, 2026
Merged

craigbarratt merged 1 commit into
custom-components:masterfrom
HoneyBearTech:fix-stopiteration

Conversation

@HoneyBearTech

@HoneyBearTech HoneyBearTech commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

What was broken
A StopIteration could never be caught in pyscript, even in the simplest script:

it = iter([])
try:
    next(it)
except StopIteration:              # never matches
    log.info("empty")
# RuntimeError: coroutine raised StopIteration

def first(items):
    for item in items:
        return item
    raise StopIteration("no items")

try:
    first([])
except StopIteration as exc:       # never matches either, and exc.value is lost
    pass
# RuntimeError: coroutine raised StopIteration

with contextlib.suppress(StopIteration):
    next(it)                       # not suppressed: RuntimeError

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's RuntimeError("generator raised StopIteration").

Why

  • pyscript evaluates every statement and expression in an async method of AstEval (aeval() and the ast_* methods).
  • Since PEP 479, Python turns a StopIteration that leaves a coroutine into RuntimeError("coroutine raised StopIteration").
  • So a StopIteration from next(), an iterator's __next__, any native function, or a script's own raise StopIteration left the coroutine it was raised in as a RuntimeError. except StopIteration never matched, and with blocks passed the RuntimeError to __exit__.
  • Python keeps the original exception, though: the RuntimeError has the StopIteration as its __cause__, and it passes unchanged through pyscript's outer coroutines, because Python only replaces a StopIteration.

What I changed
This is a rework of the first version of this PR, following @craigbarratt's suggestion: instead of catching the StopIteration everywhere pyscript's coroutines meet it, it is recovered from the RuntimeError only 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.

  • One small helper, unwrap_stop_iteration(). It recognises Python's replacement: an exception whose type is exactly RuntimeError, whose only argument is the string "coroutine raised StopIteration", and whose __cause__ is a StopIteration. It returns that StopIteration. 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.
  • It's used in four places, plus the Jupyter kernel:
    • except clauses (ast_try). Each clause is matched against the recovered exception, and that's what the as name is bound to. So except StopIteration, tuple handlers, except Exception as exc, except BaseException as exc, a subclass of StopIteration, .value and .args work as in Python, and except RuntimeError doesn'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. So contextlib.suppress(StopIteration), @contextlib.contextmanager and nullcontext() work. If __exit__ doesn't suppress it, the original error carries on. Cancelling still works as before.
    • The uncaught error report (EvalExceptionFormatter, used for the log, task.create() errors and Jupyter). It shows the StopIteration with the script's own lines and function names. Python keeps those lines on the RuntimeError's traceback, not on the StopIteration, so the report reads the replacement's traceback first and then the StopIteration'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 exc inside except StopIteration as exc makes such a loop, and without this the report itself failed with RecursionError. For raise ValueError() from exc, the report looks along the context chain for the RuntimeError that replaced exc, 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.
    • Generator expressions (genexp_loop). A StopIteration from an element, an if condition or an inner iterable is raised again from the generator, so Python itself gives RuntimeError("generator raised StopIteration"), with the StopIteration as both its __cause__ and __context__, as in Python. It is raised with a traceback that puts the RuntimeError'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 the RuntimeError isn't changed. The traceback is read and set through BaseException's own descriptor and method, as Python does internally, so a subclass's __traceback__ or with_traceback() override is never called. with passes __exit__ the traceback the same way. Before, it surfaced as RuntimeError("coroutine raised StopIteration"). The normal end of the loop and the outermost iterable work as before.
    • Jupyter (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, so ename and evalue say StopIteration and its value in both the execute_reply and the published error message.
  • The helper only recognises "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's RuntimeError is genuine and stays one.
  • Size: eval.py gets 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.py gets 4 new lines and loses 3. The first version's own commit added 648 lines to eval.py and removed 424.

Testing

  • New test_stop_iteration_matches_python in tests/test_unit_eval.py. It runs 49 scripts in CPython and in pyscript and compares every result:
    • 44 of the first version's 57 scripts, unchanged. They cover next() with and without a default; raise StopIteration, StopIteration(5) and several arguments; except StopIteration, tuple handlers, except Exception as exc, .value and .args; a bare raise and raise exc in a handler, raise ... from, handlers that clear the traceback, and finally; with and async with whose __exit__/__aexit__ sees and suppresses it, contextlib.suppress, @contextlib.contextmanager and nullcontext(); a function that raises it to its caller; native callbacks (a sorted key, functools.partial, a property, map); for loops, 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 a StopIteration subclass; __prepare__, eval(), exec() and decorators; __init__, super().__init__(), Base.__init__() and __new__; and a RuntimeError whose argument has an __eq__ that must never be called.
    • 5 new ones:
      • except BaseException as exc, a bare except:, a subclass, and except RuntimeError not catching it;
      • a RuntimeError with Python's message but no cause or another cause, and one with the async generator message and a StopIteration cause, all of which stay RuntimeError;
      • a native generator's and a native async generator's error, which stay unchanged;
      • an __exit__ that raises StopIteration itself, or returns an object whose truth test raises it;
      • a StopIteration subclass that overrides with_traceback() and __traceback__, in a generator expression and in a with block. Python uses neither override when it converts or passes on the exception, and neither does pyscript.
  • New test_stop_iteration_limits checks 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 pyscript async def that raises it and native code that awaits a pyscript function that raises it.
  • New test_stop_iteration_uncaught_report checks the error report:
    • 6 uncaught scripts are reported as StopIteration with the script line, and without RuntimeError: a plain next(), a function that raises it, a bare raise, raise exc at top level, raise exc twice in nested handlers in a function (both make a loop in the exception chain), and a native function, whose own frame is shown too;
    • an exception raised while handling one shows the StopIteration as its context, and raise ValueError() from exc shows it as its cause, with the line that raised it, also when another exception was handled in between;
    • raise ValueError() from saved after the handler has finished shows the cause without its script line (the documented limit);
    • in a generator expression, the report shows the StopIteration, with the function that raised it and its line, as the direct cause of RuntimeError: generator raised StopIteration;
    • the error task.create() logs is reported as StopIteration with the function's line.
  • test_jupyter_kernel_msgs checks that raise StopIteration(5) gives the error name StopIteration, the value 5 and a traceback ending with the script line and StopIteration: 5, in both the execute_reply and the published error message.
  • On master, the new limits, report and Jupyter tests fail, and 43 of the 49 comparison scripts fail, including those for except, with and generator expressions. The other 6 pass there too, because they check behaviour pyscript already had: the two scripts whose RuntimeError argument has an __eq__, the native callback in map(), the cause and context of a generator expression's error, a RuntimeError with Python's message but no StopIteration cause, and the native generators' errors.
  • The full test suite (235 tests), ruff, pylint, mypy, codespell and sphinx-build -W pass on Python 3.14.

Docs
A new item in Language Limitations says that StopIteration can be caught with except and suppressed by a with statement, that an uncaught one is reported as StopIteration, and that a generator expression element gives RuntimeError("generator raised StopIteration"), all as in Python. It then lists what still differs:

  • in an except clause's type, its handler and a finally block, sys.exception(), sys.exc_info() and the __context__ of a new exception are Python's RuntimeError("coroutine raised StopIteration"), not the StopIteration. A bare raise and raise exc still raise the StopIteration;
  • where Python gives that RuntimeError because a StopIteration left a native coroutine (also in a task) or a pyscript async def, except sees the StopIteration instead. The same goes for a RuntimeError with that message that a script raises from a StopIteration;
  • native code that awaits a pyscript function that raises StopIteration gets that RuntimeError;
  • an exception raised from a StopIteration after the handler that caught it has finished is reported without the StopIteration's script lines.

Note
Remaining differences from Python that this PR doesn't fix:

  • the four limits above;
  • except* (exception groups) isn't supported in pyscript, as before;
  • except BaseException only catches Exception subclasses 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.

@craigbarratt

Copy link
Copy Markdown
Member

Thanks @HoneyBearTech, this is thorough, and catching StopIteration is worth fixing. But it's a big change for it: about 270 new lines in eval.py, with catches in 18 places, and it adds a rule every future coroutine that runs native code must follow, which is easy to break later.

Python already keeps the original exception: the converted RuntimeError has the StopIteration as its __cause__, and passes unchanged through our outer coroutines. So could we unwrap it only where it matters: when matching and binding except clauses, what with passes to __exit__, the uncaught error report, and a generator expression element (which should give RuntimeError("generator raised StopIteration"))? I tried the first two on master in about 20 lines, and they pass 41 of your 57 comparison scripts, including except StopIteration, .value, except Exception as e, contextlib.suppress and a function that raises it to its caller.

The rest are mostly sys.exception()/__context__ inside a handler, and telling a genuine RuntimeError("coroutine raised StopIteration") from a native coroutine apart from the converted one. I think those are fine as documented limitations in exchange for a much smaller change.

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>
@HoneyBearTech

Copy link
Copy Markdown
Contributor Author

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 EvalStopIteration carrier and the catches spread through the interpreter are gone, and so is the rule that coroutines running native code must catch StopIteration. A future coroutine doesn't need to do anything. What's left is one 7-line helper, unwrap_stop_iteration(), and the places that use it. In all, eval.py gets 67 new lines and loses 17. 50 of the new lines are code, and the rest are comments, a docstring and blank lines. The helper only unwraps an exception whose type is exactly RuntimeError, whose only argument is the string "coroutine raised StopIteration", and whose __cause__ is a StopIteration. It never changes an exception, and an error that isn't caught carries on unchanged.

The four places you listed:

  • Matching and binding except clauses (ast_try): each clause is matched against the unwrapped exception, and that's what the as name gets. If nothing matches, the original RuntimeError carries on, and the outer catches are unchanged, so cancelling still works. Tested by the CPython comparison scripts in test_stop_iteration_matches_python.
  • What with passes to __exit__ (with_items): the unwrapped exception's type, value and traceback, for __exit__ and __aexit__. If it isn't suppressed, the original error carries on. Tested by the same comparison scripts (contextlib.suppress, @contextmanager, nullcontext(), async with, an __exit__ that raises StopIteration itself, and one whose result's truth test raises it).
  • The uncaught error report (EvalExceptionFormatter): it shows StopIteration with the script's lines. Unwrapping alone loses them, because Python keeps those frames on the RuntimeError's traceback, not on the StopIteration. So the report reads the replacement's traceback and then the StopIteration's own. Tested by test_stop_iteration_uncaught_report, which includes the error that task.create() logs.
  • A generator expression element (genexp_loop): a StopIteration from an element, an if condition or an inner iterable is raised again from the generator. So Python itself gives RuntimeError("generator raised StopIteration"), with the StopIteration as cause and context. The StopIteration is raised with a traceback that puts the RuntimeError's script frames in front of its own. That traceback is built from new traceback objects, so the RuntimeError isn't touched. It is read and set through BaseException's own descriptor and method, so a subclass's overrides aren't called. This way the report still shows the function that raised it and its line. The normal end and the outermost iterable work as before. Tested by comparison scripts 17, 38 and 47, and by the report test.

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 genexp_loop change. I also added 5 new comparison scripts: except BaseException and a subclass; a RuntimeError with Python's message but no StopIteration cause, which stays a RuntimeError; native generator errors, which stay unchanged; the two __exit__ failure cases; and a StopIteration subclass that overrides with_traceback() and __traceback__, which pyscript doesn't call, as Python doesn't. That makes 49 comparison scripts in all. The other 13 are now documented limits, in the two groups you described. test_stop_iteration_limits checks what pyscript actually does in each:

  • The exception being handled (9, 10, 19, 20, 21, 34): in an except clause's type, its handler and a finally block, sys.exception(), sys.exc_info() and a new exception's __context__ show Python's RuntimeError. In 20, except type(sys.exception()) picks a different handler because of that. A bare raise and raise exc still re-raise the StopIteration.
  • A genuine RuntimeError("coroutine raised StopIteration") (18, 22, 23, 24, 25, 26, 57): one from a native coroutine, a native task, or a script that builds the same chain itself is caught as the StopIteration. A pyscript async def that raises it is in the same group: Python would give RuntimeError there, and pyscript gives StopIteration, which fits how pyscript already runs async def like a normal function. One more fact is documented because it's the other side of the same boundary: native code that awaits a pyscript function that raises StopIteration gets the RuntimeError.

What I added beyond the four places, and why:

  • The report copes with a chain that loops back. With your approach, raise exc inside except StopIteration as exc creates a cycle: the StopIteration's context is the RuntimeError, whose cause is the same StopIteration. The existing formatter recursed on that and failed with RecursionError instead of logging the error. It now stops at an exception it has already shown. For raise ValueError() from exc, it looks along the context chain for the RuntimeError that replaced exc, so the cause is shown with its line, even when another exception was handled in between. If exc is kept and raised from after its handler has finished, that RuntimeError is no longer in the chain. The cause is then shown without its line, which is documented as a limit.
  • Jupyter's ename and evalue. The kernel already uses the formatter for the traceback, but took the name and message straight from the caught RuntimeError. It now takes them from the exception the report shows. The Jupyter test checks the reply and the published error message.
  • The helper deliberately leaves out "async generator raised StopIteration". pyscript has no async generators of its own, so that message only comes from native code, where the RuntimeError is genuine.

It merges cleanly into master. With #919, eval.py and the docs merge cleanly. The only conflict is the usual "keep both" at the end of tests/test_unit_eval.py, and the combined code passes the full suite.

@HoneyBearTech

Copy link
Copy Markdown
Contributor Author

Now that #919 is merged, I've moved this PR onto current master. The code is unchanged. Only the end of tests/test_unit_eval.py differs: it keeps #919's tests and adds these after them. It merges cleanly, and the full suite passes (235 tests).

@craigbarratt craigbarratt left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@craigbarratt
craigbarratt merged commit dece34a into custom-components:master Nov 22, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants