How do I clear all variables in the middle of a Python script?

Question:

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.

Asked By: snakile

||

Answers:

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

Answered By: John La Rooy

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

Answered By: Alex Martelli

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

Answered By: Jochen Ritzel

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.

Answered By: Jug
from IPython import get_ipython;   
get_ipython().magic('reset -sf')
Answered By: Anurag Gupta

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.

Answered By: tardis

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

Answered By: Harold Henson

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

Answered By: Kolay.Ne

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?

Answered By: Ivan

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

Answered By: Maher Hussein

This worked:

for v in dir():
    exec('del '+ v)
    del v
Answered By: David Weisser
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.