Reputation: 54521
I am looking for something similar to 'clear' in Matlab: A command/function which removes all variables from the workspace, releasing them from system memory. Is there such a thing in Python?
EDIT: I want to write a script which at some point clears all the variables.
Upvotes: 123
Views: 464264
Reputation: 1398
Note: you likely don't actually want this.
The globals()
function returns a dictionary, where keys are names of objects you can name (and values, by the way, are id
s of these objects).
The exec()
function takes a string and executes it as if you just type it in a python console. So, the code is
for i in list(globals().keys()):
if not i.startswith('_'):
exec('del ' + i)
This will remove all the objects with names not starting with underscores, including functions, classes, imported libraries, etc.
Note: you need to use list() in python 3.x to force a copy of the keys. This is because you cannot add/remove elements in a dictionary while iterating through it.
Upvotes: 3
Reputation: 37
A very easy way to delete a variable is by using the del
function.
For example
a = 30
print(a) #this would print "30"
del(a) #this deletes the variable
print(a) #now, if you try to print 'a', you will get
#an error saying 'a' is not defined
Upvotes: 0
Reputation: 1455
Isn't the easiest way to create a class contining all the needed variables? Then you have one object with all curretn variables, and if you need you can overwrite this variable?
Upvotes: 0
Reputation: 304137
No, you are best off restarting the interpreter
IPython is an excellent replacement for the bundled interpreter and has the %reset
command which usually works
Upvotes: 75
Reputation: 31
In the idle IDE there is Shell/Restart Shell. Cntrl-F6 will do it.
Upvotes: 0
Reputation: 1360
In Spyder one can configure the IPython console for each Python file to clear all variables before each execution in the Menu Run -> Configuration -> General settings -> Remove all variables before execution
.
Upvotes: 5
Reputation: 509
from IPython import get_ipython;
get_ipython().magic('reset -sf')
Upvotes: 15
Reputation: 107608
If you write a function then once you leave it all names inside disappear.
The concept is called namespace and it's so good, it made it into the Zen of Python:
Namespaces are one honking great idea -- let's do more of those!
The namespace of IPython can likewise be reset with the magic command %reset -f
. (The -f
means "force"; in other words, "don't ask me if I really want to delete all the variables, just do it.")
Upvotes: 33
Reputation: 550
This is a modified version of Alex's answer. We can save the state of a module's namespace and restore it by using the following 2 methods...
__saved_context__ = {}
def saveContext():
import sys
__saved_context__.update(sys.modules[__name__].__dict__)
def restoreContext():
import sys
names = sys.modules[__name__].__dict__.keys()
for n in names:
if n not in __saved_context__:
del sys.modules[__name__].__dict__[n]
saveContext()
hello = 'hi there'
print hello # prints "hi there" on stdout
restoreContext()
print hello # throws an exception
You can also add a line "clear = restoreContext" before calling saveContext() and clear() will work like matlab's clear.
Upvotes: 8
Reputation: 881575
The following sequence of commands does remove every name from the current module:
>>> import sys
>>> sys.modules[__name__].__dict__.clear()
I doubt you actually DO want to do this, because "every name" includes all built-ins, so there's not much you can do after such a total wipe-out. Remember, in Python there is really no such thing as a "variable" -- there are objects, of many kinds (including modules, functions, class, numbers, strings, ...), and there are names, bound to objects; what the sequence does is remove every name from a module (the corresponding objects go away if and only if every reference to them has just been removed).
Maybe you want to be more selective, but it's hard to guess exactly what you mean unless you want to be more specific. But, just to give an example:
>>> import sys
>>> this = sys.modules[__name__]
>>> for n in dir():
... if n[0]!='_': delattr(this, n)
...
>>>
This sequence leaves alone names that are private or magical, including the __builtins__
special name which houses all built-in names. So, built-ins still work -- for example:
>>> dir()
['__builtins__', '__doc__', '__name__', '__package__', 'n']
>>>
As you see, name n
(the control variable in that for
) also happens to stick around (as it's re-bound in the for
clause every time through), so it might be better to name that control variable _
, for example, to clearly show "it's special" (plus, in the interactive interpreter, name _
is re-bound anyway after every complete expression entered at the prompt, to the value of that expression, so it won't stick around for long;-).
Anyway, once you have determined exactly what it is you want to do, it's not hard to define a function for the purpose and put it in your start-up file (if you want it only in interactive sessions) or site-customize file (if you want it in every script).
Upvotes: 86