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.

1 Answer 1

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.

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

4 Comments

So with the backup variables, I am interested in knowing how that can help to delete other variables
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.
@user113531: is it what you were looking for?
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.

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.