[Python-ideas] A "local" pseudo-function
David Mertz
mertz at gnosis.cx
Sun Apr 29 16:44:18 EDT 2018
This doesn't address the fact no one actually needs it. But if we WANTED a
sublocal() context manager, we could spell it something like this:
In [42]: @contextmanager
...: def sublocal(**kws):
...: _locals = locals().copy()
...: _globals = globals().copy()
...: for k, v in kws.items():
...: if k in locals():
...: exec(f"locals()['{k}'] = {v}")
...: elif k in globals():
...: exec(f"globals()['{k}'] = {v}")
...: yield
...: locals().update(_locals)
...: globals().update(_globals)
...:
In [43]: a = 42
In [44]: with sublocal(a=43):
...: showa()
...:
43
In [45]: showa()
42
In [46]: with sublocal():
...: a = 41
...: showa()
...:
41
In [47]: showa()
42
On Sun, Apr 29, 2018 at 4:20 PM, Tim Peters <tim.peters at gmail.com> wrote:
> [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
> >
>
> 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
>
--
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons. Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180429/0faa52a1/attachment.html>
More information about the Python-ideas
mailing list