On Mon, 5 Dec 2022 at 06:04, David Mertz, Ph.D. <david.me...@gmail.com> wrote:
>
> 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
>

You're not the first to try to use globals() for this, but it means
that the context manager works ONLY at top-level. You can't do this
with it:

def foo():
    with local("abc"):
        a, b = 5, 6
        c = a + b
        d = c ** 2
        print(d)
    print(a)

and expect it to work.

(Side point, though: if you're deleting a name from globals(), why not
just delete it straight out of the dictionary rather than exec'ing?)

ChrisA
_______________________________________________
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/2XHOLRTSJV5ONH2MYZPSDX5IEF7QO75W/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to