[Python-ideas] Explicit variable capture list

Devin Jeanpierre jeanpierreda at gmail.com
Tue Jan 19 09:39:17 EST 2016


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