Confusing error message: lambda walruses

Chris Angelico rosuav at gmail.com
Sat Oct 2 19:39:38 EDT 2021


Using assignment expressions in lambda functions sometimes works, but
sometimes doesn't.

Python 3.11.0a0 (heads/main:dc878240dc, Oct  3 2021, 10:28:40) [GCC
8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

# Fine if it's a parameter to the lambda function
>>> def f():
...     return lambda x: (x, x := 2, x)
...
>>> g = f()
>>> g(1)
(1, 2, 2)

# Plain ol' SyntaxError if unparenthesized
>>> def f(n):
...     return lambda: n := 1
  File "<stdin>", line 2
    return lambda: n := 1
                     ^^
SyntaxError: invalid syntax

# Fine if it's a parameter to the outer function
>>> def f(n):
...     return lambda: (n := 1)
...
>>> g = f(3)
>>> g()
1

# But a SyntaxError if parenthesized like this??
>>> def f(n):
...     return (lambda: n := 1)
  File "<stdin>", line 2
    return (lambda: n := 1)
            ^^^^^^^^^
SyntaxError: cannot use assignment expressions with lambda

# Oh, and it doesn't actually assign anything.
>>> def f(n):
...     return (lambda: (n := 1)), (lambda: n)
...
>>> g, h = f(5)
>>> h()
5
>>> g()
1
>>> h()
5


What's going on here?

Disassembly of the last function shows that it's using STORE_FAST to
try to assign to n, so I *think* that it's actually like the first
example, where the lambda function is able to assign to its own
locals, whether they're parameters or not. But the two SyntaxErrors
are confusing.

ChrisA


More information about the Python-list mailing list