Skip to content

Commit b578e51

Browse files
authored
gh-111123: symtable should visit exception handlers before the else block (#111142)
1 parent f71cd53 commit b578e51

File tree

4 files changed

+25
-2
lines changed

4 files changed

+25
-2
lines changed

Doc/whatsnew/3.13.rst

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@ Other Language Changes
106106
the file is not accessible.
107107
(Contributed by Moonsik Park in :gh:`82367`.)
108108

109+
* Fixed a bug where a :keyword:`global` decleration in an :keyword:`except` block
110+
is rejected when the global is used in the :keyword:`else` block.
111+
(Contributed by Irit Katriel in :gh:`111123`.)
112+
109113
New Modules
110114
===========
111115

Lib/test/test_compile.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1283,6 +1283,23 @@ def test_remove_redundant_nop_edge_case(self):
12831283
def f():
12841284
a if (1 if b else c) else d
12851285

1286+
def test_global_declaration_in_except_used_in_else(self):
1287+
# See gh-111123
1288+
code = textwrap.dedent("""\
1289+
def f():
1290+
try:
1291+
pass
1292+
%s Exception:
1293+
global a
1294+
else:
1295+
print(a)
1296+
""")
1297+
1298+
g, l = {'a': 5}, {}
1299+
for kw in ("except", "except*"):
1300+
exec(code % kw, g, l);
1301+
1302+
12861303
@requires_debug_ranges()
12871304
class TestSourcePositions(unittest.TestCase):
12881305
# Ensure that compiled code snippets have correct line and column numbers
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix a bug where a :keyword:`global` declaration in an :keyword:`except` block
2+
is rejected when the global is used in the :keyword:`else` block.

Python/symtable.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1813,14 +1813,14 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
18131813
break;
18141814
case Try_kind:
18151815
VISIT_SEQ(st, stmt, s->v.Try.body);
1816-
VISIT_SEQ(st, stmt, s->v.Try.orelse);
18171816
VISIT_SEQ(st, excepthandler, s->v.Try.handlers);
1817+
VISIT_SEQ(st, stmt, s->v.Try.orelse);
18181818
VISIT_SEQ(st, stmt, s->v.Try.finalbody);
18191819
break;
18201820
case TryStar_kind:
18211821
VISIT_SEQ(st, stmt, s->v.TryStar.body);
1822-
VISIT_SEQ(st, stmt, s->v.TryStar.orelse);
18231822
VISIT_SEQ(st, excepthandler, s->v.TryStar.handlers);
1823+
VISIT_SEQ(st, stmt, s->v.TryStar.orelse);
18241824
VISIT_SEQ(st, stmt, s->v.TryStar.finalbody);
18251825
break;
18261826
case Assert_kind:

0 commit comments

Comments
 (0)