From cf198a6698e96c1cf7b472e5b8a3d92f07357a46 Mon Sep 17 00:00:00 2001 From: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:05:01 +0000 Subject: [PATCH] restore the scope when a class body raises ast_classdef switches into the class namespace before running the body and only switched back after the body finished normally. When the body raised, pyscript stayed in the class namespace, so after the exception was caught, later statements bound their names in the failed class instead of the script. Inside a function the scope stack was left one entry too long. Run the body in a try/finally so the outer scope is always restored, including for the SyntaxError raised for return or break in a class body. Add tests compared against CPython. Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com> --- custom_components/pyscript/eval.py | 16 +++-- tests/test_unit_eval.py | 103 +++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 7 deletions(-) diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index e27f4306..21700289 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -1078,13 +1078,15 @@ async def ast_classdef(self, arg): sym_table = {} self.sym_table_stack.append(self.sym_table) self.sym_table = sym_table - for arg1 in arg.body: - val = await self.aeval(arg1) - if isinstance(val, EvalReturn): - raise SyntaxError(f"{val.name()} statement outside function") - if isinstance(val, EvalStopFlow): - raise SyntaxError(f"{val.name()} statement outside loop") - self.sym_table = self.sym_table_stack.pop() + try: + for arg1 in arg.body: + val = await self.aeval(arg1) + if isinstance(val, EvalReturn): + raise SyntaxError(f"{val.name()} statement outside function") + if isinstance(val, EvalStopFlow): + raise SyntaxError(f"{val.name()} statement outside loop") + finally: + self.sym_table = self.sym_table_stack.pop() decorators = [await self.aeval(dec) for dec in arg.decorator_list] sym_table["__init__evalfunc_wrap__"] = None diff --git a/tests/test_unit_eval.py b/tests/test_unit_eval.py index 549b725f..ed0ebf96 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -2448,3 +2448,106 @@ async def test_with_exit_does_not_swallow_cancel(hass): await Function.waiter_sync() await Function.waiter_stop() await Function.reaper_stop() + + +CLASS_BODY_RAISES_SOURCE = """ +results = {} + +try: + class Foo: + a = 1 + raise ValueError("boom") +except ValueError: + pass +x = 5 +results["module"] = [x, "x" in globals()] + +def func(): + try: + class Bar: + b = 2 + raise ValueError("boom") + except ValueError: + pass + y = 7 + z = [y, "y" in locals()] + return z + +results["func"] = func() +results["func_global"] = "y" in globals() + +class Outer: + c = 3 + try: + class Inner: + d = 4 + raise ValueError("boom") + except ValueError: + pass + e = 5 + +results["nested"] = [Outer.c, Outer.e, hasattr(Outer, "d")] +""" + + +async def test_class_body_raises_matches_python(hass): + """Test that a class body that raises leaves the scope like Python, compared with CPython itself.""" + hass.data[DOMAIN] = {CONFIG_ENTRY: MockConfigEntry(domain=DOMAIN, data={CONF_ALLOW_ALL_IMPORTS: True})} + Function.init(hass) + State.init(hass) + State.register_functions() + TrigTime.init(hass) + + expected_ns = {} + exec(compile(CLASS_BODY_RAISES_SOURCE, "test", "exec"), expected_ns) # pylint: disable=exec-used + expected = expected_ns["results"] + + global_ctx = GlobalContext("test", global_sym_table={}, manager=GlobalContextMgr) + ast = AstEval("test", global_ctx=global_ctx) + Function.install_ast_funcs(ast) + ast.parse(CLASS_BODY_RAISES_SOURCE + "results\n") + assert await ast.eval() == expected + assert "x" in global_ctx.global_sym_table + assert not ast.sym_table_stack + + await Function.waiter_sync() + await Function.waiter_stop() + await Function.reaper_stop() + + +async def test_class_body_error_reaches_caller(hass): + """Test that an uncaught class body error reaches the caller and later runs are unaffected.""" + hass.data[DOMAIN] = {CONFIG_ENTRY: MockConfigEntry(domain=DOMAIN, data={CONF_ALLOW_ALL_IMPORTS: True})} + Function.init(hass) + State.init(hass) + State.register_functions() + TrigTime.init(hass) + + for source in [ + 'class Foo:\n raise ValueError("boom")\n', + "class Foo:\n return 1\n", + "class Foo:\n break\n", + ]: + with pytest.raises((ValueError, SyntaxError)): + exec(compile(source, "test", "exec"), {}) # pylint: disable=exec-used + + global_ctx = GlobalContext("test", global_sym_table={}, manager=GlobalContextMgr) + ast = AstEval("test", global_ctx=global_ctx) + Function.install_ast_funcs(ast) + for source, exc_type in [ + ('class Foo:\n raise ValueError("boom")\n', ValueError), + ("class Foo:\n for i in range(2):\n pass\n raise KeyError(1)\n", KeyError), + ]: + ast.parse(source) + with pytest.raises(exc_type): + await ast.eval() + assert ast.sym_table is ast.global_sym_table + assert not ast.sym_table_stack + + ast.parse("x = 5\nx\n") + assert await ast.eval() == 5 + assert global_ctx.global_sym_table["x"] == 5 + + await Function.waiter_sync() + await Function.waiter_stop() + await Function.reaper_stop()