[Python-ideas] Explicit variable capture list
Michael Selik
mike at selik.org
Fri Jan 22 23:58:02 EST 2016
> On Jan 22, 2016, at 11:50 PM, Andrew Barnert via Python-ideas <python-ideas at python.org> wrote:
>
> On Jan 21, 2016, at 00:48, Victor Stinner <victor.stinner at gmail.com> wrote:
>
>> Hi,
>>
>> Sorry but I'm lost in this long thread.
>
> I think the whole issue of const optimization is taking this discussion way off track, so let me try to summarize the actual issue.
>
> What the thread is ultimately looking for is a solution to the "closures capturing loop variables" problem. This problem has been in the official programming FAQ[1] for decades, as "Why do lambdas defined in a loop with different values all return the same result"?
>
> powers = [lambda x: x**i for i in range(10)]
>
> This gives you ten functions that all return x**9, which is probably not what you wanted.
The original request could have also been solved with ``functools.partial``. Sure, this is a toy solution, but the problem as originally shared was a toy problem.
>>> from functors import partial
>>> a = 1
>>> f = partial(lambda a,x: a+x, a)
>>> f(10)
11
>>> a = 2
>>> f(10)
11
Seems to me quite similar to the original suggestion from haael:
"""
a = 1
b = 2
c = 3
fun = lambda[a, b, c] x, y: a + b + c + x + y
"""
More information about the Python-ideas
mailing list