Confusing error message: lambda walruses

Peter J. Holzer hjp-python at hjp.at
Sun Oct 3 07:44:20 EDT 2021


On 2021-10-03 10:39:38 +1100, Chris Angelico wrote:
> Using assignment expressions in lambda functions sometimes works, but
> sometimes doesn't.

> ...     return lambda x: (x, x := 2, x)
syntax ok

>     return lambda: n := 1
syntax error

> ...     return lambda: (n := 1)
syntax ok

>     return (lambda: n := 1)
syntax error

> ...     return (lambda: (n := 1)), (lambda: n)
syntax ok, but doesn't assign

...
> What's going on here?

I think it's the parentheses:

The right side of the lambda is defined as an «expression», not an an
«assignment_expression», and there is no direct derivation from one to
the other in the grammar. So you can't put an «assignment_expression» there
directly. But if you put it in parentheses, it becomes a «starred_item»
which is a «starred_expression» which is then part of the «parenth_form»
which is an «enclosure» which is an «atom» which is (through several
more steps) an «expression» which can be used on the right side of a
lambda.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20211003/3d39abdb/attachment.sig>


More information about the Python-list mailing list