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

David Mertz mertz at gnosis.cx
Sun Apr 29 21:52:30 EDT 2018


On Sun, Apr 29, 2018 at 9:28 PM, Tim Peters <tim.peters at gmail.com> wrote:

> [David Mertz <mertz at gnosis.cx>]
> > Ooops. My proof [of] anti-concept has a flaw.  It only "shadows" names
> that
> > already exist.  Presumably that's the wrong idea, but it's easy enough to
> > change if desired.
>


>         with sublocal(a=6):
>             g("first in block")
>             a = 5
>             g("set a to 5")
>             b = 19
>             g("set b to 19")
>         g("after")
>
> Worm around that too, then going back to the example at the top, if
> the manager's
>
>         locals().update(_locals)
>
> had the intended effect, it would end up restoring `b` to 2 too, yes?
> The only names that "should be" restored are the names in the `kws`
> dict.
>

Actually, that wasn't my intention.  As I imagined the semantics, I wanted
a context manager that restored the "outside" context for anything defined
"inside" the context.  Allowing keyword arguments was just an extra
"convenience" that was meant to be equivalent to defining/overwriting
variables inside the body.  So these would be equivalent:

## 1
with sublocal():
    a = 1
    b = 2
    x = a + b
# a, b now have their old values again

## 2
with sublocal(a=1, b=2):
    x = a + b
# a, b now have their old values again

## 3
with sublocal(a=1):
    b = 2
    x = a + b
# a, b now have their old values again

I knew I was ignoring nonlocals and nested function scopes.  But just
trying something really simple that looks like the un-proposal in some
cases.  Maybe there's no way in pure-Python to deal with the edge cases
though.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180429/aef11416/attachment.html>


More information about the Python-ideas mailing list