List user defined variables, python

python, variables

Solution

If you don't put any underscores in front of your variables you could do:

#!/us/bin/python                                                                                    

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

for name in dir():
    if not name.startswith('__'):
        myvalue = eval(name)
        print name, "is", type(myvalue), "and is equal to ", myvalue

Problem

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?

Original source

Related problems