Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List user defined variables, python

I am trying to iterate through the variables set in a python script. I came across the following:

Enumerate or list all variables in a program of [your favorite language here]

and in the first example:

#!/us/bin/python                                                                                    

foo1 = "Hello world"
foo2 = "bar"
foo3 = {"1":"a", "2":"b"}
foo4 = "1+1"

for name in dir():
    myvalue = eval(name)
    print name, "is", type(name), "and is equal to ", myvalue

It lists all the variables stored in memory. I want to isolate the variables I have created in my script and not list the system variables created by default. Is there any way to do this?

like image 638
Mike Avatar asked Apr 24 '12 16:04

Mike


1 Answers

You can strip out variables that are included in your module by default by checking if they are in the builtin __builtins__ module, like this:

>>> x = 3
>>> set(dir()) - set(dir(__builtins__))
set(['__builtins__', 'x'])

The only thing this doesn't strip out is __builtins__ itself, which is easy to special case.

Also note that this won't work if you have re-defined any builtin names. You shouldn't do this in practice, but a lot of people do, many by accident.

like image 188
jterrace Avatar answered Oct 17 '22 00:10

jterrace