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

Python

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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

Solution 4 - Python

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

Solution 5 - Python

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.

Solution 6 - Python

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.

Solution 7 - Python

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.

Solution 8 - Python

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

Solution 9 - Python

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

Solution 10 - Python

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?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsnakileView Question on Stackoverflow
Solution 1 - PythonAlex MartelliView Answer on Stackoverflow
Solution 2 - PythonJohn La RooyView Answer on Stackoverflow
Solution 3 - PythonJochen RitzelView Answer on Stackoverflow
Solution 4 - PythonAnurag GuptaView Answer on Stackoverflow
Solution 5 - PythonJugView Answer on Stackoverflow
Solution 6 - PythontardisView Answer on Stackoverflow
Solution 7 - PythonKolay.NeView Answer on Stackoverflow
Solution 8 - PythonMaher HusseinView Answer on Stackoverflow
Solution 9 - PythonHarold HensonView Answer on Stackoverflow
Solution 10 - PythonIvanView Answer on Stackoverflow