0

How can I delete all variables in jupyter that are defined / created after a certain cell number?

My specific use case is that I will load some variables in the first few cells and I want to keep those variables, while I will experiment on the notebook.

I do not want to keep restarting or reseting the notebook as it takes time to load those variables. Instead I would like to "restart" from a certain cell.

hangc
  • 4,730
  • 10
  • 33
  • 66

1 Answers1

2

If you can afford the memory and duplicate the variables, store "backup" variables using something like copy.copy() or copy.deepcopy() and create a cell were you reallocate original values to your variables from the backups.

You'll have run this cell to restore your values.

see edit details below

For illustration:

  1. Store original values
from copy import deepcopy

bckp_a = deepcopy(var_a)
bckp_b = deepcopy(var_b)

dir_bckp = deepcopy(dir())  # store defined variables defined at this point
  1. Do you stuff
var_a = some_func(var_a)
var_b = some_other_func(var_a)
var_c = some_value
  1. Restore original values for preserved variables
var_a = deepcopy(bckp_a)
var_b = deepcopy(bckp_b)
  1. Delete newly created variables
for var in dir():
    if var == 'dir_bckp':      # Note that it is a string
        continue                   # Preserve dir_bckp, very important.
    elif var not in dir_bckp:
        del globals()[var]     # Delete newly defined variables

>>> var_c
NameError: name 'var_c' is not defined

EDIT:

If you absolutely need to delete created variables, you can try a trick with dir() and globals(). But this is probably not good practice, so be cautious.

See changes above.

Note that there is also the option of creating a restore point using Pickle, but I'm not sure of the performance if some variables take time to load.

FabienP
  • 3,018
  • 1
  • 20
  • 25
  • So with the backup variables, I am interested in knowing how that can help to delete other variables – hangc Aug 29 '17 at 16:22
  • Once variable values restored, re-run and garbage collector will do his job. If you really want to delete these variables, you can backup `dir()` and restore it. But this is a trick, I doubt it is good practice. I will explain in a edit. – FabienP Aug 29 '17 at 20:10
  • @user113531: is it what you were looking for? – FabienP Aug 30 '17 at 18:05
  • Sorry missed your reply. It is working, and doesn't sounds like a good practice to me as well. Would like to hear your idea on why it is not a good practice. – hangc Dec 16 '19 at 04:43