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:
- 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
- Do you stuff
var_a = some_func(var_a)
var_b = some_other_func(var_a)
var_c = some_value
- Restore original values for preserved variables
var_a = deepcopy(bckp_a)
var_b = deepcopy(bckp_b)
- 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.