Skip to content

gh-137570: Improve syntax error for unparenthesized assignment expression in lambda - #161927

Open
flxamartinez wants to merge 1 commit into
python:mainfrom
flxamartinez:fix-issue-137570
Open

flxamartinez wants to merge 1 commit into
python:mainfrom
flxamartinez:fix-issue-137570

Conversation

@flxamartinez

@flxamartinez flxamartinez commented Nov 13, 2026 •

Copy link
Copy Markdown

Before:

>>> lambda x: foo := 2
  File "<python-input-0>", line 1
    lambda x: foo := 2
    ^^^^^^^^^^^^^
SyntaxError: cannot use assignment expressions with lambda

After:

>>> lambda x: foo := 2
  File "<python-input-0>", line 1
    lambda x: foo := 2
              ^^^^^^^^
SyntaxError: cannot use named expression without parentheses here

The old message makes it look like you can't use := in a lambda, but you can if you add parentheses: lambda x: (foo := 2).

I added a rule for lambda ...: name := ... before the general one, so now it gives the same message as assert x := 1.

I also changed test_named_expression_invalid_15 because it was checking the old message.

This only fixes the lambda case. f(lambda: x := 1) still says "invalid syntax", and lambda x: foo.bar := 2 keeps the old message because parentheses don't fix that one. I saw that @brianschubert's idea in #146601 also covers this case.

…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.
@python-cla-bot

python-cla-bot Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant