Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -1264,6 +1264,8 @@ invalid_expression:
# Soft keywords need to also be ignored because they can be parsed as NAME NAME
| !(NAME STRING | SOFT_KEYWORD) a=disjunction b=expression_without_invalid {
_PyPegen_raise_error_for_missing_comma(p, a, b) }
| disjunction 'if' a=disjunction ':=' b=disjunction {
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "assignment expression must be parenthesized inside conditional expression" ) }
| a=disjunction 'if' b=disjunction !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") }
| a=disjunction 'if' b=disjunction 'else' !expression {
RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("expected expression after 'else', but statement is given") }
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,10 @@
Traceback (most recent call last):
SyntaxError: expected expression before 'if', but statement is given

>>> 1 if x := True else 2
Traceback (most recent call last):
SyntaxError: assignment expression must be parenthesized inside conditional expression

>>> if True:
... print("Hello"
...
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Improve :exc:`SyntaxError` message when an :ref:`assignment expression
<assignment-expressions>` is used inside the ``if`` clause of a
:ref:`conditional expression <if_expr>`. Patch by Brian Schubert.
Loading
Loading