Skip to content

Commit a87e4e5

Browse files
committed
Improve syntax error for assignment expr inside conditional expr
1 parent a17301a commit a87e4e5

File tree

4 files changed

+258
-212
lines changed

4 files changed

+258
-212
lines changed

Grammar/python.gram

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1264,6 +1264,8 @@ invalid_expression:
12641264
# Soft keywords need to also be ignored because they can be parsed as NAME NAME
12651265
| !(NAME STRING | SOFT_KEYWORD) a=disjunction b=expression_without_invalid {
12661266
_PyPegen_raise_error_for_missing_comma(p, a, b) }
1267+
| disjunction 'if' a=disjunction ':=' b=disjunction {
1268+
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "assignment expression must be parenthesized inside conditional expression" ) }
12671269
| a=disjunction 'if' b=disjunction !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") }
12681270
| a=disjunction 'if' b=disjunction 'else' !expression {
12691271
RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("expected expression after 'else', but statement is given") }

Lib/test/test_syntax.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,10 @@
180180
Traceback (most recent call last):
181181
SyntaxError: expected expression before 'if', but statement is given
182182
183+
>>> 1 if x := True else 2
184+
Traceback (most recent call last):
185+
SyntaxError: assignment expression must be parenthesized inside conditional expression
186+
183187
>>> if True:
184188
... print("Hello"
185189
...
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Improve :exc:`SyntaxError` message when an :ref:`assignment expression
2+
<assignment-expressions>` is used inside the ``if`` clause of a
3+
:ref:`conditional expression <if_expr>`. Patch by Brian Schubert.

0 commit comments

Comments
 (0)