'How to delete multiple defined and undefined variables safely in python?

I am currently using jupyter notebook, and I want to delete variables that are used only within the cell, so that I won't accidentally misuse these variables in other cells.

For example, I want to remove the variable myvar and loop variable i in the following codes:

start = 1
stop = 2
for i in range(start, stop):
    pass
myvar = "A"
# other statements
# ...
del i, myvar # Runs ok, and variables i and myvar are deleted and I won't accidentally use i or myvar in another jupyter notebook cell

This works fine, but there are cases where some variables are actually not defined. In the following example, this throws an error since i is not defined because the loop is never run. The defined variables myvar is not deleted.

start = 1
stop = 1 # Now we have stop equal to 1
for i in range(start, stop):
    pass
myvar = "A"
# other statements
# ...
del i, myvar # NameError, since i is not defined, and myvar is not deleted

I have used contextlib or try-except statements to avoid the error, but still myvar is not deleted.

import contextlib
start = 1
stop = 1
for i in range(start, stop):
    pass
myvar = "A"
# other statements
# ...
with contextlib.suppress(NameError):
    del i, myvar # Error suppressed, but myvar is not deleted

The only work-around is to wrap del statement for every variable I want to delete.

import contextlib
start = 1
stop = 1
for i in range(start, stop):
    pass
myvar = "A"
# other statements
# ...
with contextlib.suppress(NameError): 
    del i
with contextlib.suppress(NameError): 
    del myvar
# ...
# It works but codes get messy if I need to delete many variables

However, this makes codes messy, especially if you have a lot of variables to delete (n lines if there are n variables). Is there any way to delete all defined and undefined variables safely with less messy codes, in one/two lines?



Solution 1:[1]

A one-liner to do del x safely:

globals().pop('x', None);

There are many ways to do that, but they need more than 1 line of code, which I guess is not what you look for. Note ; at the end, which prevents the variable from being printed by Jupiter.

Solution 2:[2]

Rather than suppressing errors you could check if variable actually exists by checking if it is in globals() or locals(). You will have to operate string names though and form a del statement to execute it with exec.

to_delete = ['i', 'myvar']
for _var in to_delete:
    if _var in locals() or _var in globals():
        exec(f'del {_var}')

Solution 3:[3]

You can use a comma-separated listing following "del", del var1, var2, var3, to delete selected variables.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 go2nirvana
Solution 3 M. Reza Andalibi