diff --git a/Lib/test/test_syntax.py b/Lib/test/test_syntax.py index 04c759310d3d95..fe1a261df7b366 100644 --- a/Lib/test/test_syntax.py +++ b/Lib/test/test_syntax.py @@ -3186,6 +3186,29 @@ def error2(): """ self._check_error(source, "parameter and nonlocal", lineno=3) + def test_import_before_global(self): + source = """\ +def f(): + import os.path + global os +""" + self._check_error( + source, "name 'os' is assigned to before global declaration", + lineno=3, offset=5, + ) + + def test_import_before_nonlocal(self): + source = """\ +def outer(p): + def inner(): + from os import path as p + nonlocal p +""" + self._check_error( + source, "name 'p' is assigned to before nonlocal declaration", + lineno=4, offset=9, + ) + def test_raise_from_error_message(self): source = """if 1: raise AssertionError() from None diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-11-29-13-30-58.gh-issue-162598.1eZb8w.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-29-13-30-58.gh-issue-162598.1eZb8w.rst new file mode 100644 index 00000000000000..28b53a6c523c2e --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-11-29-13-30-58.gh-issue-162598.1eZb8w.rst @@ -0,0 +1,3 @@ +Raise :exc:`SyntaxError` when an :keyword:`import` statement binds a name +before its :keyword:`global` or :keyword:`nonlocal` declaration in the same +scope. diff --git a/Python/symtable.c b/Python/symtable.c index 429c204dba29b9..e56226e127da0f 100644 --- a/Python/symtable.c +++ b/Python/symtable.c @@ -2228,7 +2228,7 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s) long cur = symtable_lookup(st, name); if (cur < 0) return 0; - if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) { + if (cur & (DEF_BOUND | USE | DEF_ANNOT)) { const char* msg; if (cur & DEF_PARAM) { msg = GLOBAL_PARAM; @@ -2236,7 +2236,7 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s) msg = GLOBAL_AFTER_USE; } else if (cur & DEF_ANNOT) { msg = GLOBAL_ANNOT; - } else { /* DEF_LOCAL */ + } else { /* DEF_LOCAL or DEF_IMPORT */ msg = GLOBAL_AFTER_ASSIGN; } PyErr_Format(PyExc_SyntaxError, @@ -2261,7 +2261,7 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s) long cur = symtable_lookup(st, name); if (cur < 0) return 0; - if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) { + if (cur & (DEF_BOUND | USE | DEF_ANNOT)) { const char* msg; if (cur & DEF_PARAM) { msg = NONLOCAL_PARAM; @@ -2269,7 +2269,7 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s) msg = NONLOCAL_AFTER_USE; } else if (cur & DEF_ANNOT) { msg = NONLOCAL_ANNOT; - } else { /* DEF_LOCAL */ + } else { /* DEF_LOCAL or DEF_IMPORT */ msg = NONLOCAL_AFTER_ASSIGN; } PyErr_Format(PyExc_SyntaxError, msg, name);