List user defined variables, python
Solution 1
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
Solution 2
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.
Solution 3
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
Solution 4
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]
Mike
Updated on June 08, 2022Comments
-
Mike almost 2 years
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?
-
interjay about 12 years
dir()
doesn't give the names in__builtins__
for me (Python 2.7). All I get is['__builtins__', '__doc__', '__name__', '__package__']
. -
jterrace about 12 years@interjay it gives some other things though, like
__doc__
and__name__
that I think OP wants stripped out -
interjay about 12 yearsBut 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.