Skip to content

Commit 96469ff

Browse files
committed
gh-137570: Improve syntax error for unparenthesized assignment expression in lambda
lambda x: foo := 2 used to report 'cannot use assignment expressions with lambda', which suggests that assignment expressions are not allowed in a lambda at all. It now reports 'cannot use named expression without parentheses here', the same message used for assert x := 1.
1 parent ab48ba8 commit 96469ff

5 files changed

Lines changed: 56 additions & 1 deletion

File tree

‎Grammar/invalid.gram‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,8 @@ invalid_if_expression:
8585
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use dict unpacking on only part of a conditional expression") }
8686

8787
invalid_named_expression(memo):
88+
| 'lambda' [lambda_params] ':' a=NAME ':=' b=expression {
89+
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "cannot use named expression without parentheses here") }
8890
| a=expression ':=' expression {
8991
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(
9092
a, "cannot use assignment expressions with %s", _PyPegen_get_expr_name(a)) }

‎Lib/test/test_named_expressions.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def test_named_expression_invalid_15(self):
8989
code = """(lambda: x := 1)"""
9090

9191
with self.assertRaisesRegex(SyntaxError,
92-
"cannot use assignment expressions with lambda"):
92+
"cannot use named expression without parentheses here"):
9393
exec(code, {}, {})
9494

9595
def test_named_expression_invalid_16(self):

‎Lib/test/test_syntax.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2867,6 +2867,16 @@ def f(x: *b)
28672867
Traceback (most recent call last):
28682868
SyntaxError: cannot use named expression without parentheses here
28692869
2870+
>>> lambda x: foo := 2
2871+
Traceback (most recent call last):
2872+
SyntaxError: cannot use named expression without parentheses here
2873+
2874+
>>> lambda: x := 1
2875+
Traceback (most recent call last):
2876+
SyntaxError: cannot use named expression without parentheses here
2877+
2878+
>>> f = lambda x: (foo := 2)
2879+
28702880
>>> assert 1 = 2 = 3
28712881
Traceback (most recent call last):
28722882
SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve the :exc:`SyntaxError` message for an unparenthesized assignment
2+
expression in the body of a :keyword:`lambda`.

‎Parser/parser_invalid.c‎

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

0 commit comments

Comments
 (0)