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?