[Python-ideas] Explicit variable capture list

haael at interia.pl haael at interia.pl
Tue Jan 19 09:10:35 EST 2016


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)

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.

To make it more useful, we also need some syntax for inline lambdas. I.e.:

    a = 1
    b = 2
    c = 3
    fun = lambda[a, b, c] x, y: a + b + c + x + y

Thanks,
haael




More information about the Python-ideas mailing list