4

Is there a way to have Python print the names and values of all bound variables?

(without redesigning the program to store them all in a single list)

4 Answers 4

2

Yes you can, it is a rather dirty way to do it, but it is good for debugging etc

from pprint import pprint

def getCurrentVariableState():
    pprint(locals())
    pprint(globals())
2
  • 2
    this is not even close to all the bound variables Sep 24, 2010 at 5:39
  • @aaron Yeah definitely, those are only two scopes out of four. Built-in and non-local are missing.
    – wjandrea
    Mar 11, 2020 at 15:51
2

globals() and locals() should give you what you're looking for.

0
0
dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.
0

globals() and locals() each return a dictionary representing the symbol table in global and local scopes respectively.

0

Your Answer

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