Skip to content

Misleading SyntaxError: cannot use assignment expressions with lambda #137570

Open

Description

@wyattscarpenter

Bug report

Bug description:

Python 3.12.8 (tags/v3.12.8:2dc476b, Dec  3 2024, 19:30:04) [MSC v.1942 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> lambda x: foo := 2
  File "<stdin>", line 1
    lambda x: foo := 2
    ^^^^^^^^^^^^^
SyntaxError: cannot use assignment expressions with lambda
>>> lambda x: (foo := 2)
<function <lambda> at 0x00000229CC40E0C0>

IIRC, until today I believed that you could never use an assignment expression in a lambda. I was disabused of this notion only by reading PEP 572 itself. I believe the SyntaxError should ideally read something along the lines of "cannot use unparenthesized assignment expressions with lambda".

I wasn't sure to what category to file this under exactly, sorry if I chose wrong.

CPython versions tested on:

3.12

Operating systems tested on:

Windows

Linked PRs

Activity

  1. terryjreedy commented on Aug 9, 2025

    @terryjreedy
    Member

    I agree that the error message should include 'unparenthesized'.

  2. terryjreedy commented on Aug 9, 2025

    @terryjreedy
    Member

    Valid back to at least 3.8, and using the binding, even somewhat sensibly, is possible.

    >>> (lambda x: ((foo := 2*x), foo**2))(3)
    (6, 36)
    >>> (lambda x: foo if (foo := 2*x) > 5 else foo**2)(3)
    6
    
  3. serhiy-storchaka commented on Aug 9, 2025

    @serhiy-storchaka
    Member

    It is parsed as (lambda x: foo) := 2. So, including 'unparenthesized' will not help -- assignment to parenthesized lambda does not work either.

    Other ambiguous examples, such as a = b := c or a, b := c, raise just "invalid syntax".

  4. wyattscarpenter commented on Aug 9, 2025

    @wyattscarpenter
    Author

    @serhiy-storchaka It's the assignment expression that should be described as unparenthesized, not the lambda expression :)

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)topic-parsertype-bugAn unexpected behavior, bug, or error

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions