On Thu, 1 Dec 2022 at 06:47, Benedict Verhegghe <bver...@gmail.com> wrote:
>
> A context manager could be used for this. On exit it should delete the
> variables created inside it. Someting like this:
>
> class Scope:
>      def __enter__(self):
>          self._globals = list(globals().keys())
>          return self
>      def __exit__(self, exc_type, exc_value, traceback):
>          del_vars = [var for var in globals()
>                      if var not in self._globals]
>          for var in del_vars:
>              del globals()[var]
>
> Then one can write:
>
> with Scope():
>      a = 1
>      with Scope():
>          b = 2
>      # no more b here
> # no more a or b here
>
> Maybe such an (optimized) context manager could be added to Python?
>

That only works if the Scope class is defined in the same module that
you use it, and you only use it at top level. It won't work if
imported into another module, nor in a function. Also, it won't allow
shadowing of outer names with inner names, a standard feature of most
scoping systems (and all sane ones):

x = 1
def spam():
    x = 2
    def ham():
        x = 3
        print("In ham, x is", x)
    ham()
    print("In spam, x is", x)
spam()
print("At top level, x is", x)

Simply removing x from globals will not reveal the previous value.

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/D3YRABARPPRVD3P5GVPAGJJ5PBIKILND/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to