Reputation: 37
I am using Jupyter Notebook and want to delete all the variables created after a certain point. I am able to do it using a for-loop looping through dir()
and comparing it to the checkpoint that I create at the cell using checkpoint = list(dir())
.
My goal is to clear the environment without losing the libraries that I import in the beginning (which is where I create my checkpoint). Anything I want to retain further, I can add to the checkpoint list and delete the rest.
The issue is, I don't want to write the same for-loop again whenever I want to clear the variables. As soon as I wrap that loop in a function, it stops working. There is no error; but there is no effect either.
Loop:
for i in list(dir()):
if i not in checkpoint:
exec('del {}'.format(i))
The same loop wrapped in a function:
def clear_variables():
for i in list(dir()):
if i not in checkpoint:
exec('del {}'.format(i))
The loop works. The function doesn't.
Upvotes: 2
Views: 583
Reputation: 114330
It sounds like you are trying to update your global dictionary. You can't safely delete values from a dictionary while you're iterating over it, so you can make a copy of the keys first:
def clear_setpoint(keep, globals=globals()):
keep = set(keep)
for key in list(globals.keys()):
if key not in keep:
del globals[key]
If your only goal is to preserve imported modules, you don't even need to create a checkpoint:
from types import ModuleType, FunctionType
def clear_all(globals=globals()):
for key in list(globals.keys()):
value = globals[key]
if not isinstance(value, (ModuleType, FunctionType, type)) or \
(isinstance(value, FunctionType, type) and value.__module__ == globals['__name__'] and value.__name__ != 'clear_all'):
del globals[key]
This version will automatically delete anything that is not a function, module or class. Classes and functions that are in the current module, based on their __module__
attribute, are deleted as well. Other classes and functions are l And of course, you don't want to delete the function itself :)
kely to be imported, so are not deleted. This won't preserve imported constants, like if you do from math import pi
. You can combine the two approaches to preserve imports like that.
Upvotes: 2