[Python-ideas] A "local" pseudo-function

Chris Angelico rosuav at gmail.com
Sun Apr 29 16:15:50 EDT 2018


On Mon, Apr 30, 2018 at 5:55 AM, Tim Peters <tim.peters at gmail.com> wrote:
> [Tim]
>>> Then `c` is 12, but `a` is still 1 and `b` is still 2.  Same thing in the end:
>>>
>>> c = local(a=3, b=4, a*b)
>
> [Nikolaus Rath <Nikolaus at rath.org>]
>> I think this can be done already with slighly different syntax:
>>
>> c = (lambda a=3, b=4: a*b)()
>>
>> The trailing () is a little ugly, but the semantics are much more
>> obvious.
>
> But also broken, in a way that can't be sanely fixed.  Covered before
> in other messages.  Short course:
>
>>>> a = 10
>>>> b = 20
>>>> (lambda a=3, b=a+1: (a, b))()
> (3, 11)
>
> This context really demands (3, 4) instead.  In Scheme terms, Python's
> lambda default arguments do "let" binding ("all at once"), but "let*"
> binding is what's needed ("one at a time, left to right, with bindings
> already done visible to later bindings").

So maybe the effective semantics should be:

>>> (lambda a=3: (lambda b=a+1: (a, b))())()
(3, 4)

ChrisA


More information about the Python-ideas mailing list