Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 67 additions & 17 deletions custom_components/pyscript/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,11 @@
"PUT",
}

#
# the message of the RuntimeError that Python raises when a StopIteration leaves a coroutine
#
STOP_ITERATION_REPLACED = "coroutine raised StopIteration"

#
# AstEval attributes that hold the scope a generator expression's elements are evaluated in
#
Expand Down Expand Up @@ -393,6 +398,9 @@ def pyscript_property(obj, attr, hook):
SUPER_THISCLASS = super.__dict__["__thisclass__"].__get__
TYPE_MRO = type.__dict__["__mro__"].__get__
TYPE_DICT = type.__dict__["__dict__"].__get__
# an exception subclass can override these, which Python doesn't use when it raises or converts one
EXC_TRACEBACK = BaseException.__dict__["__traceback__"].__get__
EXC_WITH_TRACEBACK = BaseException.with_traceback


def super_property(sup, attr):
Expand Down Expand Up @@ -424,6 +432,15 @@ def super_property(sup, attr):
return None


def unwrap_stop_iteration(exc):
"""Return the StopIteration that Python replaced when it left one of our coroutines, else exc."""
# pylint: disable=unidiomatic-typecheck
if type(exc) is RuntimeError and issubclass(type(exc.__cause__), StopIteration) and len(exc.args) == 1:
if type(exc.args[0]) is str and exc.args[0] == STOP_ITERATION_REPLACED:
return exc.__cause__
return exc


class EvalName:
"""Identifier that hasn't yet been resolved."""

Expand Down Expand Up @@ -1554,14 +1571,16 @@ async def ast_try(self, arg):
if isinstance(val, EvalStopFlow):
return val
except Exception as err:
# match and bind the StopIteration Python replaced; if nothing matches, raise err unchanged
visible_err = unwrap_stop_iteration(err)
for handler in arg.handlers:
match = False
if handler.type:
exc_list = await self.aeval(handler.type)
if not isinstance(exc_list, tuple):
exc_list = [exc_list]
for exc in exc_list:
if isinstance(err, exc):
if isinstance(visible_err, exc):
match = True
break
else:
Expand All @@ -1571,9 +1590,9 @@ async def ast_try(self, arg):
if handler.name in self.sym_table and isinstance(
self.sym_table[handler.name], EvalLocalVar
):
self.sym_table[handler.name].set(err)
self.sym_table[handler.name].set(visible_err)
else:
self.sym_table[handler.name] = err
self.sym_table[handler.name] = visible_err
try:
for arg1 in handler.body:
val = await self.aeval(arg1)
Expand Down Expand Up @@ -1642,8 +1661,10 @@ async def with_items(self, arg, items, async_attr):
# unlike Python, the exit can't suppress these, so tasks can always be stopped
await self.call_func(exit_func, exit_attr, manager, *sys.exc_info())
raise
except Exception: # pylint: disable=broad-exception-caught
if not await self.call_func(exit_func, exit_attr, manager, *sys.exc_info()):
except Exception as err: # pylint: disable=broad-exception-caught
# pass __exit__ the StopIteration Python replaced; if it isn't suppressed, raise err unchanged
exc = unwrap_stop_iteration(err)
if not await self.call_func(exit_func, exit_attr, manager, type(exc), exc, EXC_TRACEBACK(exc)):
raise
return None
await self.call_func(exit_func, exit_attr, manager, None, None, None)
Expand Down Expand Up @@ -2334,10 +2355,23 @@ def genexp_loop(self, arg, iters, loop_vars, gen_vars, gen_scope, scope, loop):
gen_scope.saved = outer_vars
self.loop_scopes = gen_loop_scopes
coro = self.genexp_next(arg, iters)
stop = None
try:
coro.send(None) # pylint: disable=no-member
except StopIteration as exc:
elt = exc.value
except RuntimeError as exc:
# an element, a condition or an inner iterable raised StopIteration
stop = unwrap_stop_iteration(exc)
if stop is exc:
raise
# keep the script frames, which are on the RuntimeError's traceback, before its own
stop_tb, frames, tb = EXC_TRACEBACK(stop), [], exc.__traceback__
while tb:
frames.append(tb)
tb = tb.tb_next
for tb in reversed(frames):
stop_tb = TracebackType(stop_tb, tb.tb_frame, tb.tb_lasti, tb.tb_lineno)
else:
#
# the element has to wait, which can't be done here, so stop it; whatever
Expand All @@ -2360,6 +2394,9 @@ def genexp_loop(self, arg, iters, loop_vars, gen_vars, gen_scope, scope, loop):
loop_scope.set_bindings(bindings)
for attr, value in save_scope.items():
setattr(self, attr, value)
if stop is not None:
# raised outside the handler, so Python gives RuntimeError("generator raised StopIteration")
raise EXC_WITH_TRACEBACK(stop, stop_tb)
if not elt:
return
yield elt[0]
Expand Down Expand Up @@ -2843,9 +2880,10 @@ def dump(self, this_ast=None):
class EvalExceptionFormatter:
"""Format exceptions using pyscript-aware traceback frames."""

def __init__(self, exc: BaseException) -> None:
def __init__(self, exc: BaseException, seen: set[int] | None = None) -> None:
"""Initialize exception formatter state."""
self.exc = exc
# show the StopIteration Python replaced, with the script frames from the replacement's traceback
self.exc = unwrap_stop_iteration(exc)

self.current_func: str | None = None
self.current_code_list: list[str] | None = None
Expand All @@ -2856,15 +2894,29 @@ def __init__(self, exc: BaseException) -> None:
self.end_col_offset: int = 0

self.stack = traceback.StackSummary()
self._build_stack()
self._build_stack(exc.__traceback__)
if self.exc is not exc:
self._build_stack(self.exc.__traceback__)
self.chained_msg: str | None = None
self.chained_exc: EvalExceptionFormatter | None = None
if exc.__cause__ is not None:
self.chained_msg = traceback._cause_message
self.chained_exc = EvalExceptionFormatter(exc.__cause__)
elif exc.__context__ is not None and not exc.__suppress_context__:
self.chained_msg = traceback._context_message
self.chained_exc = EvalExceptionFormatter(exc.__context__)
# stop if the chain loops back, eg, after "raise exc" in "except StopIteration as exc"
seen = set() if seen is None else seen
seen.update((id(exc), id(self.exc)))
chained, chained_msg = self.exc.__cause__, traceback._cause_message
if chained is None and not self.exc.__suppress_context__:
chained, chained_msg = self.exc.__context__, traceback._context_message
elif chained is not None:
# eg, "raise ValueError() from exc": the script frames are on what replaced exc, in the context
context, walked = self.exc.__context__, set()
while context is not None and id(context) not in walked:
if unwrap_stop_iteration(context) is chained:
chained = context
break
walked.add(id(context))
context = context.__context__
if chained is not None and not seen.intersection((id(chained), id(unwrap_stop_iteration(chained)))):
self.chained_msg = chained_msg
self.chained_exc = EvalExceptionFormatter(chained, seen)

def format(self) -> list[str]:
"""Return formatted traceback lines for this exception."""
Expand All @@ -2883,10 +2935,8 @@ def format(self) -> list[str]:

return result

def _build_stack(self) -> None:
def _build_stack(self, current_tb: TracebackType | None) -> None:
"""Build stack summary from traceback frames."""
current_tb = self.exc.__traceback__

while current_tb:
frame = current_tb.tb_frame
code = frame.f_code
Expand Down
7 changes: 4 additions & 3 deletions custom_components/pyscript/jupyter_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,8 @@ async def shell_handler(self, shell_socket, wire_msg):
self.global_ctx.set_auto_start(True)
self.global_ctx.start()
except Exception as exc:
traceback_mesg = EvalExceptionFormatter(exc).format()
formatter = EvalExceptionFormatter(exc)
traceback_mesg = formatter.format()

metadata = {
"dependencies_met": True,
Expand All @@ -374,8 +375,8 @@ async def shell_handler(self, shell_socket, wire_msg):
content = {
"execution_count": self.execution_count,
"status": "error",
"ename": type(exc).__name__, # Exception name, as a string
"evalue": str(exc), # Exception value, as a string
"ename": type(formatter.exc).__name__, # Exception name, as a string
"evalue": str(formatter.exc), # Exception value, as a string
"traceback": traceback_mesg,
}
_LOGGER.debug("Executing '%s' got exception: %s", code, content)
Expand Down
15 changes: 15 additions & 0 deletions docs/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2472,6 +2472,21 @@ it doesn't faithfully mimic Python. Here are some areas where pyscript differs
- A context manager's ``__exit__`` (or ``__aexit__``) is called when a task is cancelled, but returning
a true value doesn't suppress ``CancelledError``, ``KeyboardInterrupt`` or ``SystemExit`` the way it
does in Python. This ensures pyscript tasks can always be stopped.
- ``StopIteration`` can be caught with ``except`` (e.g., ``except StopIteration as exc``, then ``exc.value``)
and suppressed by a ``with`` statement (e.g., ``contextlib.suppress(StopIteration)``), as in Python, and
an uncaught one is reported as ``StopIteration``. In a generator expression element, it gives
``RuntimeError("generator raised StopIteration")``, as in Python. What still differs from Python:

- 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, as it does for a
``RuntimeError`` with that message raised ``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.
- Generator expressions (e.g., ``any(x > 3 for x in values)``) work and are lazy, as in Python: each
element is evaluated only when it's asked for, so ``any()`` stops at the first match. Since functions
like ``sum()`` or ``any()`` ask for each element without waiting, an element can't wait for anything
Expand Down
24 changes: 24 additions & 0 deletions tests/test_jupyter.py
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,30 @@ async def test_jupyter_kernel_msgs(hass, caplog, socket_enabled):
reply = await shell_msg(sock, "execute_request", {"code": "xyz"}, execute=True)
assert reply["content"]["evalue"] == "name 'xyz' is not defined"

#
# an uncaught StopIteration is reported as itself, in the reply and in the published error
#
await send(
sock["shell_port"],
"execute_request",
{"code": "x = 1\nraise StopIteration(5)"},
parent_header={},
identities={},
)
assert (await get_iopub_msg(sock, "status"))["content"]["execution_state"] == "busy"
await get_iopub_msg(sock, "execute_input")
error = await get_iopub_msg(sock, "error")
reply = deserialize_wire_msg(await sock["shell_port"].recv_multipart())
assert reply["header"]["msg_type"] == "execute_reply"
assert (await get_iopub_msg(sock, "status"))["content"]["execution_state"] == "idle"
for content in [reply["content"], error["content"]]:
assert [content["ename"], content["evalue"]] == ["StopIteration", "5"]
assert content["traceback"][-2:] == [
' File "jupyter_0", line 2, in None\n raise StopIteration(5)\n',
"StopIteration: 5\n",
]
assert "RuntimeError" not in "".join(content["traceback"])

#
# syntax error
#
Expand Down
Loading
Loading