From b578e51f026a45576930816d6784697192ed472e Mon Sep 17 00:00:00 2001 From: Irit Katriel <1055913+iritkatriel@users.noreply.github.com> Date: Sat, 21 Oct 2023 13:38:29 +0100 Subject: gh-111123: symtable should visit exception handlers before the else block (#111142) --- Doc/whatsnew/3.13.rst | 4 ++++ Lib/test/test_compile.py | 17 +++++++++++++++++ .../2023-10-20-23-14-06.gh-issue-111123.jjVc3M.rst | 2 ++ Python/symtable.c | 4 ++-- 4 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2023-10-20-23-14-06.gh-issue-111123.jjVc3M.rst diff --git a/Doc/whatsnew/3.13.rst b/Doc/whatsnew/3.13.rst index 5da5f93..e830c91 100644 --- a/Doc/whatsnew/3.13.rst +++ b/Doc/whatsnew/3.13.rst @@ -106,6 +106,10 @@ Other Language Changes the file is not accessible. (Contributed by Moonsik Park in :gh:`82367`.) +* Fixed a bug where a :keyword:`global` decleration in an :keyword:`except` block + is rejected when the global is used in the :keyword:`else` block. + (Contributed by Irit Katriel in :gh:`111123`.) + New Modules =========== diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py index c4452e3..df6e5e4 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -1283,6 +1283,23 @@ class TestSpecifics(unittest.TestCase): def f(): a if (1 if b else c) else d + def test_global_declaration_in_except_used_in_else(self): + # See gh-111123 + code = textwrap.dedent("""\ + def f(): + try: + pass + %s Exception: + global a + else: + print(a) + """) + + g, l = {'a': 5}, {} + for kw in ("except", "except*"): + exec(code % kw, g, l); + + @requires_debug_ranges() class TestSourcePositions(unittest.TestCase): # Ensure that compiled code snippets have correct line and column numbers diff --git a/Misc/NEWS.d/next/Core and Builtins/2023-10-20-23-14-06.gh-issue-111123.jjVc3M.rst b/Misc/NEWS.d/next/Core and Builtins/2023-10-20-23-14-06.gh-issue-111123.jjVc3M.rst new file mode 100644 index 0000000..f2cebe2 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2023-10-20-23-14-06.gh-issue-111123.jjVc3M.rst @@ -0,0 +1,2 @@ +Fix a bug where a :keyword:`global` declaration in an :keyword:`except` block +is rejected when the global is used in the :keyword:`else` block. diff --git a/Python/symtable.c b/Python/symtable.c index 75ea9e9..da7fec0 100644 --- a/Python/symtable.c +++ b/Python/symtable.c @@ -1813,14 +1813,14 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s) break; case Try_kind: VISIT_SEQ(st, stmt, s->v.Try.body); - VISIT_SEQ(st, stmt, s->v.Try.orelse); VISIT_SEQ(st, excepthandler, s->v.Try.handlers); + VISIT_SEQ(st, stmt, s->v.Try.orelse); VISIT_SEQ(st, stmt, s->v.Try.finalbody); break; case TryStar_kind: VISIT_SEQ(st, stmt, s->v.TryStar.body); - VISIT_SEQ(st, stmt, s->v.TryStar.orelse); VISIT_SEQ(st, excepthandler, s->v.TryStar.handlers); + VISIT_SEQ(st, stmt, s->v.TryStar.orelse); VISIT_SEQ(st, stmt, s->v.TryStar.finalbody); break; case Assert_kind: -- cgit v0.12