[Python-ideas] Explicit variable capture list

Nick Coghlan ncoghlan at gmail.com
Wed Jan 20 01:37:48 EST 2016


On 20 January 2016 at 10:38, Chris Angelico <rosuav at gmail.com> wrote:
> Big one for the bike-shedding: Is this "capture as local" (the same
> semantics as the default arg - if you rebind it, it changes for the
> current invocation only), or "capture as static" (the same semantics
> as a closure if you use the 'nonlocal' directive - if you rebind it,
> it stays changed), or "capture as constant" (what people are usually
> going to be doing anyway)?

The "shared value" approach can already be achieved by binding a
mutable object rather than an immutable one, and there's no runtime
speed difference between looking up a local and looking up a constant,
so I think it makes sense to just stick with "default argument
semantics, but without altering the function signature"

One possible name for such a directive would be "sharedlocal": it's in
most respects a local variable, but the given definition time
initialisation value is shared across all invocations to the function.

With that spelling:

    def f(*, len=len):
         ...

Would become:

    def f():
        sharedlocal len=len
        ...

And you'd also be able to do things like:

    def f():
        sharedlocal cache={}

Alternatively, if we just wanted to support early binding of
pre-existing names, then "bindlocal" could work:

    def f():
        bindlocal len
        ...

Either approach could be used to handle early binding of loop
iteration variables:

    for i in range(10):
        def f():
            sharedlocal i=i
            ...

    for i in range(10):
        def f():
            bindlocal i
            ...

I'd be -1 on bindlocal (I think dynamic optimisers like PyPy or Numba,
or static ones like Victor's FAT Python project are better answers
there), but "sharedlocal" is more interesting, since it means you can
avoid creating a closure if all you need is to persist a bit of state
between invocations of a function.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list