Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
8 changes: 4 additions & 4 deletions Python/symtable.c
Original file line number Diff line number Diff line change
Expand Up @@ -2228,15 +2228,15 @@ 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;
} else if (cur & USE) {
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,
Expand All @@ -2261,15 +2261,15 @@ 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;
} else if (cur & USE) {
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);
Expand Down
Loading