8

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?

cel
  • 30,017
  • 18
  • 97
  • 117
David W
  • 111
  • 2
  • 6
  • There isn't, but you could [define your own magic command](http://ipython.org/ipython-doc/3/config/custommagics.html#defining-magics). – Thomas K May 13 '15 at 18:18

2 Answers2

2

%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_).*$

  • Works like a charm! For further clarification of what the regex syntax means here: https://stackoverflow.com/a/6830819/7382307 – billjoie Jan 30 '22 at 05:39
1

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.

Alvin Wanda
  • 179
  • 2
  • 9
  • 1
    Cool stuff! Maybe obvious to you guys but one should also add `save_list.append('save_list')` to avoid error. :) – V. Foy Feb 03 '22 at 10:35
  • now that you mention it, it seems really silly that I didn't include that in the answer. Good catch! – Alvin Wanda Mar 05 '22 at 09:11