5

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?

1

5 Answers 5

10

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
Sign up to request clarification or add additional context in comments.

Comments

9

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.

3 Comments

dir() doesn't give the names in __builtins__ for me (Python 2.7). All I get is ['__builtins__', '__doc__', '__name__', '__package__'].
@interjay it gives some other things though, like __doc__ and __name__ that I think OP wants stripped out
But that has nothing to do with __builtins__, they are just names which are defined in every module (and therefore happen to be in __builtins__ as well). Calling them "builtin variables" is misleading.
2

Here is solution.

#!/us/bin/python    

not_my_data = set(dir())

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

my_data = set(dir()) - not_my_data

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

but this is bad practice.

You should use something like

#!/us/bin/python    
my_data = dict()                                                                                   
my_data['foo1'] = "Hello world"
my_data['foo2'] = "bar"
my_data['foo1'] = {"1":"a", "2":"b"}
my_data['foo1'] = "1+1"

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

Comments

1

The question title leads me to see this. But this is not what I wanted.

self-answering is below

[s for s in dir() if not '__' in s]

Comments

0

I wanted something more along the lines of matlab 'whos', so I baked this up: gist here

import __main__
def whos(lss):
 fil = __main__.__file__
 thisthinghere = open(fil).read().split("\n")
 vs = []
 for l in thisthinghere:
    if l.find("=") > -1:
        vs.append(l.split("=")[0].strip())
 keys = lss.keys()
 out = {}
 for v in vs:
    try: 
        out[v] = lss[v]
    except:
        "not in list"
 keys = out.keys()
 keys.sort()
 for k in keys:
    val = str(out[k])
    if len (val) > 10:
        if val[-1] == ")":val = val[0:10]+"..."+val[-10:]
        elif val[-1] == "]" :val = val[0:10]+"..."+val[-10:]
        else: val = val[0:10]
    print k,":",val

 return out

#import into your script and call with whos(locals())

it seems to work. it will print the variable space, and it returns it as a dictionary for easy pickling/jsoning.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.