[Python-ideas] Explicit variable capture list

Devin Jeanpierre jeanpierreda at gmail.com
Tue Jan 19 09:45:59 EST 2016


Sorry, forget the first part entirely, I was still confused when I
wrote it. Definitely the semantics of values are very different, but
they don't matter for this.

I think the rough equivalent of the capture-by-copy C++ lambda is the
function definition I provided with default values.

-- Devin

On Tue, Jan 19, 2016 at 6:39 AM, Devin Jeanpierre
<jeanpierreda at gmail.com> wrote:
> On Tue, Jan 19, 2016 at 6:10 AM, <haael at interia.pl> wrote:
>>
>>
>> Hi
>>
>> C++ has a nice feature of explicit variable capture list for lambdas:
>>
>>     int a = 1, b = 2, c = 3;
>>     auto fun = [a, b, c](int x, int y){ return a + b + c + x + y};
>>
>> This allows easy construction of closures. In Python to achieve that, you need to say:
>
> This is worded very confusingly. Python has easy construction of
> closures with implicit variable capture.
>
> The difference has to do with "value semantics" in C++, which Python
> doesn't have. If you were using int* variables in your C++ example,
> you'd have the same semantics as Python does with its int references.
>
>>     def make_closure(a, b, c):
>>         def fun(x, y):
>>             return a + b + c + x + y
>>         return def
>>     a = 1
>>     b = 2
>>     c = 3
>>     fun = make_closure(a, b, c)
>
> The usual workaround is actually:
>
>   a = 1
>   b = 1
>   c = 1
>   def fun(x, y, a=a, b=b, c=c):
>       return a + b + c + x + y
>
> -- Devin


More information about the Python-ideas mailing list