Confusing error message: lambda walruses

Peter J. Holzer hjp-python at hjp.at
Sun Oct 3 08:02:18 EDT 2021


On 2021-10-03 10:39:38 +1100, Chris Angelico wrote:
> # 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

I thought about that one a bit more and I think that the lambda is
creating a new scope, just like a regular function would, so it is
assigning to its own private «n», not the «n» in «f(n)».

https://docs.python.org/3/reference/expressions.html#grammar-token-lambda-expr
doesn't mention scope explicitely, but

|    The unnamed object behaves like a function object defined with:
|
|    def <lambda>(parameters):
|        return expression

implies to me that it should create a new scope because a nested function
defined with «def» would do that, too.

        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/2c31815f/attachment.sig>


More information about the Python-list mailing list