Like most commenters, I think the whole "create an anonymous function then
call it" scoping thing is too complex and has too many edge cases to be a
good idea.

That said, I decided to play around with what I can do to serve the general
purpose within existing Python:

>>> @contextmanager
... def local(pats=["scoped_*"]):
...     try:
...         yield
...     finally:
...         for _var in list(globals()):
...             for pat in pats:
...                 if fnmatch(_var, pat):
...                     exec(f"del {_var}", globals())
...
>>> with local(['a', 'b', 'c']):
...     a, b = 5, 6
...     c = a + b
...     d = c**2
...     print(d)
...
121
>>> a
Traceback (most recent call last):
  Cell In [37], line 1
    a
NameError: name 'a' is not defined

>>> d
121


Clearly, this still leaves it up to the programmer to make sure the "local"
names aren't already defined and important (i.e. with other values
already).  I guess you could make this more complex by copying globals(),
then restoring those that previously existed, even if they were defined
otherwise within the context.  But honestly, for the very limited purpose
desired, this implementation seems like plenty.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/XCXHGD4QRNNDXSWTGHWAKJBIIE2KWZPB/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to