[Python-ideas] Local scope for statement blocks

Chris Angelico rosuav at gmail.com
Tue Mar 4 04:52:49 CET 2014


On Tue, Mar 4, 2014 at 2:39 PM, Brian Nguyen <musicdenotation at gmail.com> wrote:
> do:
>     nonlocal x
>     k = init
>     for i in list:
>         k = f(i,k)
>         n = f2(n,k)

You may need to elaborate a bit, especially as you have a declaration
regarding 'x' and never use x anywhere. But if, as I suspect, you
intend for this to have local k/i/n and fetch init/list/f/f2 from its
parent scope, then this is something that's been discussed a few
times. With the current implementation of CPython, the easiest and
cleanest way to do this is with a closure. You could spell 'do' like
this:

def do(f):
    f()

@do
def _():
    nonlocal x
    k = init
    for i in list:
        k = f(i,k)
        n = f2(n,k)

Put that inside a function and it'll do most of what I think you're saying.

ChrisA


More information about the Python-ideas mailing list