Skip to content

Commit 14f1c55

Browse files
committed
[3.14] pythongh-138944: Fix SyntaxError message for invalid syntax following valid import-as statement (pythonGH-138945)
(cherry picked from commit 3dab11f) Co-authored-by: Brian Schubert <[email protected]>
1 parent 842c49b commit 14f1c55

File tree

4 files changed

+60
-19
lines changed

4 files changed

+60
-19
lines changed

Grammar/python.gram

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1387,11 +1387,11 @@ invalid_import:
13871387
| 'import' token=NEWLINE {
13881388
RAISE_SYNTAX_ERROR_STARTING_FROM(token, "Expected one or more names after 'import'") }
13891389
invalid_dotted_as_name:
1390-
| dotted_name 'as' !(NAME (',' | ')' | NEWLINE)) a=expression {
1390+
| dotted_name 'as' !(NAME (',' | ')' | ';' | NEWLINE)) a=expression {
13911391
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a,
13921392
"cannot use %s as import target", _PyPegen_get_expr_name(a)) }
13931393
invalid_import_from_as_name:
1394-
| NAME 'as' !(NAME (',' | ')' | NEWLINE)) a=expression {
1394+
| NAME 'as' !(NAME (',' | ')' | ';' | NEWLINE)) a=expression {
13951395
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a,
13961396
"cannot use %s as import target", _PyPegen_get_expr_name(a)) }
13971397

Lib/test/test_syntax.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2111,6 +2111,25 @@
21112111
Traceback (most recent call last):
21122112
SyntaxError: cannot use subscript as import target
21132113
2114+
# Check that we don't raise a "cannot use name as import target" error
2115+
# if there is an error in an unrelated statement after ';'
2116+
2117+
>>> import a as b; None = 1
2118+
Traceback (most recent call last):
2119+
SyntaxError: cannot assign to None
2120+
2121+
>>> import a, b as c; d = 1; None = 1
2122+
Traceback (most recent call last):
2123+
SyntaxError: cannot assign to None
2124+
2125+
>>> from a import b as c; None = 1
2126+
Traceback (most recent call last):
2127+
SyntaxError: cannot assign to None
2128+
2129+
>>> from a import b, c as d; e = 1; None = 1
2130+
Traceback (most recent call last):
2131+
SyntaxError: cannot assign to None
2132+
21142133
# Check that we dont raise the "trailing comma" error if there is more
21152134
# input to the left of the valid part that we parsed.
21162135
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix :exc:`SyntaxError` message when invalid syntax appears on the same line
2+
as a valid ``import ... as ...`` or ``from ... import ... as ...``
3+
statement. Patch by Brian Schubert.

Parser/parser.c

Lines changed: 36 additions & 17 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)