ActiveState Code

Recipe 576700: print variables as a dictionarly


Often I need to print some diagnostic variables and have to construct a format string to include both name and value; but there is a quicker way! This is especially useful for tracing function call values (foo in example below)

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def get_names_dict(*args):
    id2name = dict((id(val), key) for key, val in inspect.stack()[1][0].f_locals.items())
    return dict((id2name[id(a)], a) for a in args)

# >>> a = 1
# >>> b = 'b'
# >>> print get_names_dict(a, b)
# {'a': 1, 'b': 'b'}

def foo(a, b, c, d, e):
    #something interesting here



def main(argv):
    a, b, c, d, e = get_some_interesting_values()
    print 'calling foo with ', get_names_dict(a, b, c, d, e)
    foo(a, b, c, d, e)

Discussion

I found is very convenient since the only difference with foo() call is the function name, all the vars are easily copy-pasted.

There is a potential flaw in the recipe if multiple references are assigned to the same variable (and will have the same id). There are a few reasonable things one can do - I am open to suggestions; but practically speaking this has not bothered me.

Comments

  1. 1. At 12:56 p.m. on 27 mar 2009, Michael Shepanski said:

    Another useful tool when you have a class is to __dict__.

    class SomeClass: def __init__(self): self.a = "foobar" self.b = 5 self.c = 65

    myClass = SomeClass() print myClass.__dict__

  2. 2. At 2 a.m. on 29 mar 2009, Agnius Vasiliauskas said:

    What about built-in functions- locals() and vars(). Don`t they fits your needs ?

Sign in to comment