How can we print a variable name along with its value in python, which will be useful when debugging?

I wrote something like this several times:

print 'customer id: ', customerId

I want to have a function that prints the name of a variable along with the value

>>myprint(customerId)

>>customerId: 12345
+4
source share
2 answers

Doing exactly what you require involves finding O (n) in the character table, which is terrible IMHO.

If you can pass the string corresponding to the variable name, you can do this:

import sys

def myprint(name, mod=sys.modules[__name__]):
    print('{}: {}'.format(name, getattr(mod, name)))

Test:

a=535
b='foo'
c=3.3

myprint('a')
myprint('b')
myprint('c')

It will be printed:

a: 535
b: foo
c: 3.3

You can also use it to print variables from another module by passing a second argument, for example:

>>> import os
>>> myprint('pathsep', os)
pathsep: :
+6
source

, , , .

(?) :

import re
regex = re.compile("__(.+)")
def check_value(checkpoint_name):
    print "============"
    print checkpoint_name
    print "============"
    for variable_name, variable_value in globals().items():
        if regex.match(variable_name) is None:
            print "%s\t:\t%s" % (variable_name, str(variable_value))
    print "============"

. ,

 a = 0
 check_value("checkpoint after definition of a")

 b = 1
 check_value("checkpoint after definition of b")

. , , , ...

0

All Articles