I was able to define an unset() function / method (similar to that in PHP), except I could pass in the variable / object / class name as a string. This method deletes the target string from Pyton's globals.
I am not sure if this is terrible practice, but it worked for the purpose of deleting things I've defined in a Jupyter notebook.
def unset(varname):
"""
Unsets a global variable from memory. Helpful when we are running code blocks in Jupyter multiple times.
"""
try:
del globals()[varname]
print('deleted ' + varname)
except:
print(varname + ' does not exist')
Here are some examples with a class definition and an instance:
class MyTest:
somevar = 1234
def __init__(self):
print('MyTest')
myT = MyTest()
unset('MyTest')
This will output:
MyTest
deleted MyTest
You can see if the instance is still defined:
print(myT)
It is, and the output is something like:
<main.MyTest object at 0x107bd54d0>
You can then unset the instance object:
unset('myT')
Output:
deleted myT
Comments and suggestions are welcome!
gc
is Python's garbage-collection for in-memory objects, only - it's not even a 'cache' in the sense of 'persists in files'. Whereas jupyter is running under your web browser which has an entirely different cache (or 'temporary internet files' as some OSs call them). You wouldn't expect changing the oil on your car to change the radio presets, either... – Kraigkrait