Skip to content

Commit cf8f36f

Browse files
authored
gh-138716: Fix assert a := b syntax error message (#138718)
1 parent 1ce0553 commit cf8f36f

File tree

4 files changed

+262
-173
lines changed

4 files changed

+262
-173
lines changed

Grammar/python.gram

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1315,6 +1315,14 @@ invalid_assert_stmt:
13151315
a, b,
13161316
"cannot assign to %s here. Maybe you meant '==' instead of '='?",
13171317
_PyPegen_get_expr_name(a)) }
1318+
| 'assert' a=expression ':=' b=expression {
1319+
RAISE_SYNTAX_ERROR_KNOWN_RANGE(
1320+
a, b,
1321+
"cannot use named expression without parentheses here") }
1322+
| 'assert' expression ',' a=expression ':=' b=expression {
1323+
RAISE_SYNTAX_ERROR_KNOWN_RANGE(
1324+
a, b,
1325+
"cannot use named expression without parentheses here") }
13181326
invalid_block:
13191327
| NEWLINE !INDENT { RAISE_INDENTATION_ERROR("expected an indented block") }
13201328
invalid_comprehension:

Lib/test/test_syntax.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2690,10 +2690,15 @@ def f(x: *b)
26902690
Asserts:
26912691
26922692
>>> assert (a := 1) # ok
2693-
>>> # TODO(@sobolevn): improve this message in the next PR
2693+
>>> assert 1, (a := 1) # ok
2694+
26942695
>>> assert a := 1
26952696
Traceback (most recent call last):
2696-
SyntaxError: invalid syntax
2697+
SyntaxError: cannot use named expression without parentheses here
2698+
2699+
>>> assert 1, a := 1
2700+
Traceback (most recent call last):
2701+
SyntaxError: cannot use named expression without parentheses here
26972702
26982703
>>> assert 1 = 2 = 3
26992704
Traceback (most recent call last):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve :exc:`SyntaxError` message for :keyword:`assert` in cases like
2+
``assert a := b``.

0 commit comments

Comments
 (0)