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
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.
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.
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: :
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With