'Clear all except for a few specific variables in IPython
I'm aware of the %reset
and %reset_selective
commands in IPython
. However, let's say you have many variables and you want to clear all variables except x
, y
, z
. Is there a concise way to accomplish this?
Say a %reset_all_except x,y,z
?
Solution 1:[1]
%reset_selective
accepts RegEx.
If you have variables named as: glob_x, glob_y, glob_z
which you don't want to reset, you can use: %reset_selective -f ^(?!glob_).*$
Solution 2:[2]
this is a collective answer based off a ton of similar questions:
capture default variables in the system AND the name of the list that will save the variables to be preserved (should be your very first lines of code):
save_list = dir()
save_list.append('save_list') #thanks @V.Foy!
add other variables you want to save to the list before the "clear variables" command is used:
save_list.append(*your_variable_to_be_saved*)
finally, clear all variables (except default and saved) with:
for name in dir():
if name not in save_list:
del globals()[name]
for name in dir():
if name not in save_list:
del locals()[name]
this will clear all variables except the default and those you choose to save. whenever i did that without saving default variables, it cleared those too and i had to restart kernel to get them back.
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 |