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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With