Skip to content

Commit de2aea0

Browse files
authored
bpo-34939: Allow annotated global names in module namespace (GH-9844)
Allow annotated global names in the module namespace after the symbol is declared as global. Previously, only symbols annotated before they are declared as global (i.e. inside a function) were allowed. This change allows symbols to be declared as global before the annotation happens in the global scope.
1 parent bd036d3 commit de2aea0

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

Lib/test/test_symtable.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,20 @@ def test_annotated(self):
144144
self.assertTrue(st4.lookup('x').is_local())
145145
self.assertFalse(st4.lookup('x').is_annotated())
146146

147+
# Test that annotations in the global scope are valid after the
148+
# variable is declared as nonlocal.
149+
st5 = symtable.symtable('global x\nx: int', 'test', 'exec')
150+
self.assertTrue(st5.lookup("x").is_global())
151+
152+
# Test that annotations for nonlocals are valid after the
153+
# variable is declared as nonlocal.
154+
st6 = symtable.symtable('def g():\n'
155+
' x = 2\n'
156+
' def f():\n'
157+
' nonlocal x\n'
158+
' x: int',
159+
'test', 'exec')
160+
147161
def test_imported(self):
148162
self.assertTrue(self.top.lookup("sys").is_imported())
149163

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Allow annotated names in module namespace that are declared global before
2+
the annotation happens. Patch by Pablo Galindo.

Python/symtable.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1175,6 +1175,7 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
11751175
VISIT_QUIT(st, 0);
11761176
}
11771177
if ((cur & (DEF_GLOBAL | DEF_NONLOCAL))
1178+
&& (st->st_cur->ste_symbols != st->st_global)
11781179
&& s->v.AnnAssign.simple) {
11791180
PyErr_Format(PyExc_SyntaxError,
11801181
cur & DEF_GLOBAL ? GLOBAL_ANNOT : NONLOCAL_ANNOT,

0 commit comments

Comments
 (0)