Delete Variables from Python Console Programmatically in PyQGIS

pyqgisqgis-python-console

I often use the Python Console for running some lines of code and I also use some prints for checking the validity of the results.

If I run this sample code:

a = 2
b = 4
res = a + b
print res

it will print the value of the res variable in the Python Console. However, if I then close the script tab, the res variable is still there. This means that, if I type print res in the Python Console, it will still return the last stored value.

I know that I can type:

del res

from the Python Console for deleting it. In fact, if I then type print res, I get:

NameError: name 'res' is not defined

as expected, but this is useful only when dealing with one or two variables and if I remember the names of these variables.


After a few searches, I found these questions:

How to clear python console in QGIS?

Clearing Python Console in QGIS using Python Command

but their answers only explain how to clear the Python Console and not how to delete the variables.


Is there a programmatic way for deleting all the variables stored during the current QGIS session?

Best Answer

In addition to @bcollins answer, if you want to change your variables you have defined inside the QGIS python console you can try this approach:

Define a variable which holds all variables before you start programming:

my_dir = dir()

Do your magic with gis, for example:

 my_variable = 42
 my_other_variable = "foo"

Then do something like this:

for varis in dir():
   if varis not in my_dir and varis != "my_dir":
        print varis 
        exec("%s = None" % str(varis)) # set them to None 

This way you get the all the variables which are NOT in my_dir and don't remove any other variables that were added by QGIS.

Update: With the suggestion of @jon_two I try to combine the method of @bcollins and mine. This would be something like:

## after you finished your magic
my_new_dir = list(dir())
for varis in my_new_dir:
   if varis not in my_dir and varis != "my_dir":
        del locals()[varis]
Related Question