getting the name of a variable

Jason Orendorff jason at jorendorff.com
Thu Dec 6 13:07:15 EST 2001


Sandy Norton wrote:
> When I'm debugging I'm always sticking stuff like "print 'x:', x" 
> in my code.

Try this.

import inspect
import sys
import re

_out_re = re.compile(r"^out\s*\(\s*(.*)\s*\)$")

def out(variable):
    """ Prints variable name and value to sys.stderr. """
    frame, filename, lineno, fnname, lines, i = inspect.stack(1)[1]
    my_line = lines[i].strip()
    match = _out_re.match(my_line)
    if match:
        my_line = match.group(1)
    print >> sys.stderr, "%s: %r" % (my_line, variable)

This works by loading the source code of the caller from its
source file.  So if you call out() from the Python prompt, it fails.
Try using it in an actual program or module instead.

-- 
Cheers,
Jason Orendorff
http://www.jorendorff.com/





More information about the Python-list mailing list