5

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
Kumar Deepak
  • 473
  • 4
  • 18
  • 1
    @Kasra he has many variables he dosen't want to do the same typing instead want to call a function – The6thSense Jun 30 '15 at 08:50
  • 1
    What if `12345` is referenced by more than one name? Or none (e.g. only referenced via a list)? Read this: http://nedbatchelder.com/text/names.html – jonrsharpe Jun 30 '15 at 08:54
  • `test_str = 'hello'; myprint(test_str);` what will happen ? the `TrueValue` of the variable `test_str`, which is `"hello"` , will be passed to the function `myprint`, not along with the `VariableName`. – Lyfing Jun 30 '15 at 08:54
  • @jonrsharpe thats what I am talking – The6thSense Jun 30 '15 at 08:54

2 Answers2

8

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: :
fferri
  • 18,285
  • 5
  • 46
  • 95
1

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...

Patrick the Cat
  • 2,138
  • 1
  • 16
  • 33