Deleting variables from the Python Console in a programmatic way?

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]

There are a couple of builtin functions you should consider for this.

dir() will gives you the list of in scope variables
globals() will give you a dictionary of global variables
locals() will give you a dictionary of local variables

but you may run into trouble because you could inadvertently delete some variables that QGIS sets. So something like this could get you started:

>>> my_var_res = 4
>>> my_vars = [v for v in locals().keys() if v.startswith('my_var')]
['my_var_res']
>>> for v in my_vars:
        del locals()[v]

I'm not claiming this is a good thing to do, just that it is possible


A method which I used a while ago was to begin each variable name with an underscore ("_"). As there are no other variables beginning with a single underscore (only double), you can search for all these variables and delete them accordingly:

# Define user variables
_foo1 = "Hello world"
_foo2 = "bar"
_foo3 = {"1":"a", "2":"b"}
_foo4 = "1+1"

# Create list containing user variables
my_vars = []
for var in dir():
    if var.startswith('_') and not var.startswith('__'):
        my_vars.append(var)

# Delete specific user variable
for x in my_vars:
    if '_foo1' in x:
        del globals()[x]

# Delete all user variables
for x in my_vars:
    del globals()[x]