Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have written something like this multiple times:

print 'customer id: ', customerId

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

>>myprint(customerId)

>>customerId: 12345
like image 759
Kumar Deepak Avatar asked Jun 30 '15 08:06

Kumar Deepak


People also ask

How do you print variable names and values in Python?

Using f-strings in Python to print variables is the most commonly used method and I would personally recommend using this method. In this method, an 'f' is placed before the opening quotation mark of a string. Braces {} are placed around the names of variables that you are looking to print.

How do you print the value of a variable in Python?

You first include the character f before the opening and closing quotation marks, inside the print() function. To print a variable with a string in one line, you again include the character f in the same place – right before the quotation marks.


2 Answers

Doing exactly what you require involves a O(n) lookup in the symbol 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')

Will print:

a: 535
b: foo
c: 3.3

You can use it also for printing variables from another module by passing the second argument, e.g.:

>>> import os
>>> myprint('pathsep', os)
pathsep: :
like image 134
fferri Avatar answered Oct 20 '22 10:10

fferri


Basically you need to hand-type the variable name into your helper function's argument every time you call it, which makes it the same as directly formatting the strings into a printed message.

Another possible (useless?) heck can be the following:

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 "============"

,which prints all non-system-protected, declared variables in global scope per call. To call the function, do

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

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

Feel free to customize the function for your need. I just came up with this, not sure if this works the way you want...

like image 39
Patrick the Cat Avatar answered Oct 20 '22 11:10

Patrick the Cat