[Python-ideas] A "local" pseudo-function

Tim Peters tim.peters at gmail.com
Sun Apr 29 16:20:14 EDT 2018


[Ethan Furman <ethan at stoneleaf.us>]
> If we need a sublocal scope, I think the most Pythonic* route to have it
> would be:
>
>     with sublocal():
>         blah blah
>
> which would act just like local/global does now:
>
>   - any assignment creates a new variable
>     - unless that variable has been declared global/nonlocal
>   - plain reads (no assignment ever happens) refer to
> nonlocal/global/built-in names
> ...

As covered most recently in an exchange with Tim Delaney, best I can
tell absolutely nobody has wanted that.  By "sublocal scope" they
don't mean a full-fledged new scope at all, but a kind of limited
"shadowing" of a handful of specific, explicitly given names.  It acts
like a context manager, if there were a way to clearly spell

    save the current state of these specific identifiers at the start (& I
        couldn't care less whether they're local, nonlocal, or global - I
        don't know & don't care)

    then execute the code exactly as if this gimmick had never been used

    then, at the end, restore the specific identifier states we saved
at the start

It's the same kind of shadowing Python already does by magic for, e.g., `i`, in

    [i for i in range(3)]

So, e.g.,

"""
a = 42

def showa():
    print(a)

def run():
    global a

    local a: # assuming this existed
        a = 43
        showa()
    showa()
"""

would print 43 and then 42.  Which makes "local a:" sound senseless on
the face of it ;-)  "shadow" would be a more descriptive name for what
it actually does.

> ...


More information about the Python-ideas mailing list