93
votes

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.

9
It'll be helpful if you changed your title to something like "How do I clear all variables in the middle of a Python script?" for future searches on the topic, because "How to restart the command window in Python?" has nothing to do with what you're actually asking. - Sam Dolan
Can you provide any possible context in which this makes sense? - S.Lott
Sounds like another case of trying to move coding habits from their native environment to one where they don't make any sense. - Glenn Maynard
If you're just concerned about some massive objects (images or other huge arrays), you could del them when you're done. If you're simply worried about the namespace being cluttered, you should probably reconsider your design using so many names. For example, for a series of image transforms, keeping every interim step is likely unnecessary. - Nick T
@S.Lott: exploratory scientific analysis in a console. It's common to end up with many un-wanted variables (after trying things, and then deciding that's not a relevant pathway). But in this case, John La Rooy's answer is the most appropriate. - naught101

9 Answers

75
votes

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).

66
votes

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

30
votes

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.")

12
votes
from IPython import get_ipython;   
get_ipython().magic('reset -sf')
5
votes

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.

3
votes

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.

2
votes

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 ids 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 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.

0
votes

In the idle IDE there is Shell/Restart Shell. Cntrl-F6 will do it.

0
votes

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?