]> granicus.if.org Git - python/commitdiff
bpo-34939: Allow annotated global names in module namespace (GH-9844)
authorPablo Galindo <Pablogsal@gmail.com>
Sun, 14 Oct 2018 17:01:03 +0000 (18:01 +0100)
committerGitHub <noreply@github.com>
Sun, 14 Oct 2018 17:01:03 +0000 (18:01 +0100)
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.

Lib/test/test_symtable.py
Misc/NEWS.d/next/Core and Builtins/2018-10-13-17-40-15.bpo-34939.0gpxlJ.rst [new file with mode: 0644]
Python/symtable.c

index 2cd735bdc508b2e44d40afacb7440b86eca839bf..8d76f6fe45f9b45b21020c281fdd057e22915951 100644 (file)
@@ -144,6 +144,20 @@ class SymtableTest(unittest.TestCase):
         self.assertTrue(st4.lookup('x').is_local())
         self.assertFalse(st4.lookup('x').is_annotated())
 
+        # Test that annotations in the global scope are valid after the
+        # variable is declared as nonlocal.
+        st5 = symtable.symtable('global x\nx: int', 'test', 'exec')
+        self.assertTrue(st5.lookup("x").is_global())
+
+        # Test that annotations for nonlocals are valid after the
+        # variable is declared as nonlocal.
+        st6 = symtable.symtable('def g():\n'
+                                '    x = 2\n'
+                                '    def f():\n'
+                                '        nonlocal x\n'
+                                '    x: int',
+                                'test', 'exec')
+
     def test_imported(self):
         self.assertTrue(self.top.lookup("sys").is_imported())
 
diff --git a/Misc/NEWS.d/next/Core and Builtins/2018-10-13-17-40-15.bpo-34939.0gpxlJ.rst b/Misc/NEWS.d/next/Core and Builtins/2018-10-13-17-40-15.bpo-34939.0gpxlJ.rst
new file mode 100644 (file)
index 0000000..b588f72
--- /dev/null
@@ -0,0 +1,2 @@
+Allow annotated names in module namespace that are declared global before
+the annotation happens. Patch by Pablo Galindo.
index d74f26fbe35a227d835c022e4736c97b71207c74..dc934a556daa07a63ab03366f23562aeb3bc72b0 100644 (file)
@@ -1175,6 +1175,7 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
                 VISIT_QUIT(st, 0);
             }
             if ((cur & (DEF_GLOBAL | DEF_NONLOCAL))
+                && (st->st_cur->ste_symbols != st->st_global)
                 && s->v.AnnAssign.simple) {
                 PyErr_Format(PyExc_SyntaxError,
                              cur & DEF_GLOBAL ? GLOBAL_ANNOT : NONLOCAL_ANNOT,