10

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?

2
  • stackoverflow.com/questions/843277/… you can check if variable exist before deleting it Commented Oct 29, 2020 at 15:59
  • You can check with if 'i' in locals() or use try: del i with except NameError: pass. I'd use the try/except style. But I honestly would not delete variables at all. Define a function for logical units of code, then the variable will be deleted once the function has finished. Or delete your variables at places where they are defined for sure. Commented Oct 29, 2020 at 16:00

3 Answers 3

13

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

Sign up to request clarification or add additional context in comments.

2 Comments

The question references this functionality, and rather than asking if it exists, is asking if there is a way to delete multiple variables whether or not some or all have been defined.
^ This comment is a good critique in terms of the original question, but this is the top result for some internet searches for the simpler "defined-variable-only" question, and this answer is very effective for that. +1
4

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.

1 Comment

this doesn't delete variables from dict
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}')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.