Skip to content

Commit 845272c

Browse files
committed
gh-162598: Reject imports that bind a name before its global or nonlocal declaration
1 parent 0423fc6 commit 845272c

3 files changed

Lines changed: 30 additions & 4 deletions

File tree

‎Lib/test/test_syntax.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3186,6 +3186,29 @@ def error2():
31863186
"""
31873187
self._check_error(source, "parameter and nonlocal", lineno=3)
31883188

3189+
def test_import_before_global(self):
3190+
source = """\
3191+
def f():
3192+
import os.path
3193+
global os
3194+
"""
3195+
self._check_error(
3196+
source, "name 'os' is assigned to before global declaration",
3197+
lineno=3, offset=5,
3198+
)
3199+
3200+
def test_import_before_nonlocal(self):
3201+
source = """\
3202+
def outer(p):
3203+
def inner():
3204+
from os import path as p
3205+
nonlocal p
3206+
"""
3207+
self._check_error(
3208+
source, "name 'p' is assigned to before nonlocal declaration",
3209+
lineno=4, offset=9,
3210+
)
3211+
31893212
def test_raise_from_error_message(self):
31903213
source = """if 1:
31913214
raise AssertionError() from None
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Raise :exc:`SyntaxError` when an :keyword:`import` statement binds a name
2+
before its :keyword:`global` or :keyword:`nonlocal` declaration in the same
3+
scope.

‎Python/symtable.c‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2228,15 +2228,15 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
22282228
long cur = symtable_lookup(st, name);
22292229
if (cur < 0)
22302230
return 0;
2231-
if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) {
2231+
if (cur & (DEF_BOUND | USE | DEF_ANNOT)) {
22322232
const char* msg;
22332233
if (cur & DEF_PARAM) {
22342234
msg = GLOBAL_PARAM;
22352235
} else if (cur & USE) {
22362236
msg = GLOBAL_AFTER_USE;
22372237
} else if (cur & DEF_ANNOT) {
22382238
msg = GLOBAL_ANNOT;
2239-
} else { /* DEF_LOCAL */
2239+
} else { /* DEF_LOCAL or DEF_IMPORT */
22402240
msg = GLOBAL_AFTER_ASSIGN;
22412241
}
22422242
PyErr_Format(PyExc_SyntaxError,
@@ -2261,15 +2261,15 @@ symtable_visit_stmt(struct symtable *st, stmt_ty s)
22612261
long cur = symtable_lookup(st, name);
22622262
if (cur < 0)
22632263
return 0;
2264-
if (cur & (DEF_PARAM | DEF_LOCAL | USE | DEF_ANNOT)) {
2264+
if (cur & (DEF_BOUND | USE | DEF_ANNOT)) {
22652265
const char* msg;
22662266
if (cur & DEF_PARAM) {
22672267
msg = NONLOCAL_PARAM;
22682268
} else if (cur & USE) {
22692269
msg = NONLOCAL_AFTER_USE;
22702270
} else if (cur & DEF_ANNOT) {
22712271
msg = NONLOCAL_ANNOT;
2272-
} else { /* DEF_LOCAL */
2272+
} else { /* DEF_LOCAL or DEF_IMPORT */
22732273
msg = NONLOCAL_AFTER_ASSIGN;
22742274
}
22752275
PyErr_Format(PyExc_SyntaxError, msg, name);

0 commit comments

Comments
 (0)