Skip to content

Restore the scope when a class body raises - #906

Open
HoneyBearTech wants to merge 1 commit into
custom-components:masterfrom
HoneyBearTech:fix-classdef-scope
Open

HoneyBearTech wants to merge 1 commit into
custom-components:masterfrom
HoneyBearTech:fix-classdef-scope

Conversation

@HoneyBearTech

Copy link
Copy Markdown
Contributor

What was broken
When a class body raises, pyscript stayed in the class's namespace. After the exception was caught, later statements bound their names in the failed class instead of the script:

try:
    class Foo:
        raise ValueError("boom")
except ValueError:
    pass

x = 5   # ended up in the failed class's namespace, not in globals

Inside a function, the scope stack was left one entry too long.

Why
ast_classdef pushes the current symbol table and switches into the class namespace before running the body, but it only switched back after the body finished normally.

What I changed
The class body now runs in a try/finally, so the outer scope is always restored, including for the SyntaxError raised for return or break in a class body.

Testing

  • Two new tests in tests/test_unit_eval.py, compared against CPython:
    • a class body that raises, caught at module level, in a function, and in a nested class;
    • an uncaught error reaching the caller, with the next evaluation unaffected.
  • The full test suite, ruff, pylint, mypy and codespell pass on Python 3.14.

Note
#902's second commit also changes ast_classdef. Whichever merges second needs a small rebase; I'm happy to do it.

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>
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.

1 participant