Skip to content

Commit 3dab11f

Browse files
gh-138944: Fix SyntaxError message for invalid syntax following valid import-as statement (#138945)
1 parent 9d34623 commit 3dab11f

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
@@ -1416,11 +1416,11 @@ invalid_import:
14161416
| 'import' token=NEWLINE {
14171417
RAISE_SYNTAX_ERROR_STARTING_FROM(token, "Expected one or more names after 'import'") }
14181418
invalid_dotted_as_name:
1419-
| dotted_name 'as' !(NAME (',' | ')' | NEWLINE)) a=expression {
1419+
| dotted_name 'as' !(NAME (',' | ')' | ';' | NEWLINE)) a=expression {
14201420
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a,
14211421
"cannot use %s as import target", _PyPegen_get_expr_name(a)) }
14221422
invalid_import_from_as_name:
1423-
| NAME 'as' !(NAME (',' | ')' | NEWLINE)) a=expression {
1423+
| NAME 'as' !(NAME (',' | ')' | ';' | NEWLINE)) a=expression {
14241424
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a,
14251425
"cannot use %s as import target", _PyPegen_get_expr_name(a)) }
14261426

Lib/test/test_syntax.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2163,6 +2163,25 @@
21632163
Traceback (most recent call last):
21642164
SyntaxError: cannot use subscript as import target
21652165
2166+
# Check that we don't raise a "cannot use name as import target" error
2167+
# if there is an error in an unrelated statement after ';'
2168+
2169+
>>> import a as b; None = 1
2170+
Traceback (most recent call last):
2171+
SyntaxError: cannot assign to None
2172+
2173+
>>> import a, b as c; d = 1; None = 1
2174+
Traceback (most recent call last):
2175+
SyntaxError: cannot assign to None
2176+
2177+
>>> from a import b as c; None = 1
2178+
Traceback (most recent call last):
2179+
SyntaxError: cannot assign to None
2180+
2181+
>>> from a import b, c as d; e = 1; None = 1
2182+
Traceback (most recent call last):
2183+
SyntaxError: cannot assign to None
2184+
21662185
# Check that we dont raise the "trailing comma" error if there is more
21672186
# input to the left of the valid part that we parsed.
21682187
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)