2

For Python 2.7 I have a little utility for debugging:

def printvar(label, var):
    print "%s:\n%s" % (label, pformat(var))

Often I call it like printvar("foo", foo).

Is it possible to simplify that a tiny bit and only pass in the variable, like printvar(foo), but still have it print the name of the variable? Using introspection or something?

Philip
  • 1,691
  • 4
  • 21
  • 41

1 Answers1

0

You can't do that, but you can approximate the reverse: pass in only the label, and have it grab the actual value. Here's a quick version:

def printvar(label):
    for frame in inspect.getouterframes(inspect.currentframe())[1:]:
        local_vars = frame[0].f_locals
        if label in local_vars:
            print "%s:\n%s" % (label, frame[0].f_locals[label])
            return
    raise NameError("No such variable")

Then you can do this:

def foo():
    x = 2
    printvar('x')

>>> foo()
x:
2

This is, of course, very hacky business: the code looks through the local-variable namespaces of every stack frame in its call chain. Normally this kind of trickery is to be avoided, but for debugging purposes it can be useful in a pinch.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384