Home » Python » Viewing all defined variables [duplicate]

Viewing all defined variables [duplicate]

Posted by: admin November 1, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

Couple of things you could use:

  • dir() will give you the list of in scope variables:
  • globals() will give you a dictionary of global variables
  • locals() will give you a dictionary of local variables
Questions:
Answers:

If this is an option for you, you might want to look at IPython:

To get a list of all currently defined variables, type who:

In [1]: foo = 'bar'

In [2]: who
foo

You can type whos for more detail:

In [3]: whos
Variable   Type    Data/Info
----------------------------
foo        str     bar

There are a wealth of other functions available – basically it is the Python interpreter on steroids. One convenient one is store command, which lets you save variables between sessions (kind of like a super easy pickle)

If you have a few minutes, check out Jeff Rush’s excellent IPython demonstration screencasts:

I am in no way associated with the team behind IPython, just a satisfied user.

Questions:
Answers:

As RedBlueThing and analog said:

  • dir() gives a list of in scope variables
  • globals() gives a dictionary of global variables
  • locals() gives a dictionary of local variables

Using the interactive shell (version 2.6.9), after creating variables a = 1 and b = 2, running dir() gives

['__builtins__', '__doc__', '__name__', '__package__', 'a', 'b']

running locals() gives

{'a': 1, 'b': 2, '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, '__name__': '__main__', '__doc__': None}

Running globals() gives exactly the same answer as locals() in this case.

I haven’t gotten into any modules, so all the variables are available as both local and global variables. locals() and globals() list the values of the variables as well as the names; dir() only lists the names.

If I import a module and run locals() or globals() inside the module, dir() still gives only a small number of variables; it adds __file__ to the variables listed above. locals() and globals() also list the same variables, but in the process of printing out the dictionary value for __builtin__, it lists a far larger number of variables: built-in functions, exceptions, and types such as “'type': <type 'type'>“, rather than just the brief <module '__builtin__' (built-in)> as shown above.

For more about dir() see Python 2.7 quick reference at New Mexico Tech or the dir() function at ibiblio.org.

For more about locals() and globals() see locals and globals at Dive Into Python and a page about globals at New Mexico Tech.

[Comment: @Kurt: You gave a link to enumerate-or-list-all-variables-in-a-program-of-your-favorite-language-here but that answer has a mistake in it. The problem there is: type(name) in that example will always return <type 'str'>. You do get a list of the variables, which answers the question, but with incorrect types listed beside them. This was not obvious in your example because all the variables happened to be strings anyway; however, what it’s returning is the type of the name of the variable instead of the type of the variable. To fix this: instead of print type(name) use print eval('type(' + name + ')'). I apologize for posting a comment in the answer section but I don’t have comment posting privileges, and the other question is closed.]

Questions:
Answers:

To get the names:

for name in vars().keys():
  print(name)

To get the values:

for value in vars().values():
  print(value)

vars() also takes an optional argument to find out which vars are defined within an object itself.

Questions:
Answers:

print locals()

edit continued from comment.

To make it look a little prettier when printing:

import sys, pprint
sys.displayhook = pprint.pprint
locals()

That should give you a more vertical printout.

Questions:
Answers:

keep in mind dir() will return all current imports, AND variables.

if you just want your variables, I would suggest a naming scheme that is easy to extract from dir, such as varScore, varNames, etc.

that way, you can simply do this:

for vars in dir():
 if vars.startswith("var"):
   print vars

Edit

if you want to list all variables, but exclude imported modules and variables such as:

__builtins__

you can use something like so:

import os
import re

x = 11
imports = "os","re"

for vars in dir():
    if vars.startswith("__") == 0 and vars not in imports:
        print vars

as you can see, it will show the variable “imports” though, because it is a variable (well, a tuple). A quick workaround is to add the word “imports” into the imports tuple itself!

Questions:
Answers:

In my Python 2.7 interpreter, the same whos command that exists in MATLAB exists in Python. It shows the same details as the MATLAB analog (variable name, type, and value/data).

In the Python interpreter, whos lists all variables in the “interactive namespace”.

Questions:
Answers:

a bit more smart (python 3) way:

def printvars():

   tmp = globals().copy()
   [print(k,'  :  ',v,' type:' , type(v)) for k,v in tmp.items() if not k.startswith('_') and k!='tmp' and k!='In' and k!='Out' and not hasattr(v, '__call__')]

Questions:
Answers:

globals(), locals(), vars(), and dir() may all help you in what you want.

Questions:
Answers:
def MyWho():
     print [v for v in globals().keys() if not v.startswith('_')]

This has to be defined in the interactive shell.

import os, a = 10, import sys, MyWho() then gives

[‘a’, ‘MyWho’, ‘sys’, ‘os’]