[Python-ideas] Explicit variable capture list
Terry Reedy
tjreedy at udel.edu
Tue Jan 19 10:23:36 EST 2016
On 1/19/2016 9: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:
>
> 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 purpose of writing a make_closure function is so it can be called
more than once, to make more than one closure.
f123 = make_closure(1, 2, 3)
f456 = make_closure(4, 5, 6)
> My proposal: create a special variable qualifier (like global and nonlocal) to automatically capture variables
>
> a = 1
> b = 2
> c = 3
> def fun(x, y):
> capture a, b, c
> return a + b + c + x + y
>
> This will have an effect that symbols a, b and c in the body of the function have values as they had at the moment of function creation. The variables a, b, c must be defined at the time of function creation. If they are not, an error is thrown. The 'capture' qualifier may be combined with keywords global and nonlocal to change lookup behaviour.
This only allows one version of fun, not multiple, so it is not
equivalent at all. As Devin stated, it is equivalent to to using
parameters with default argument values.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list