getting the name of a variable

Sandy Norton sandskyfly at hotmail.com
Fri Dec 7 02:04:54 EST 2001


Thanks Jason,

Your sweet function does exactly what I need. I really do recommend
you upload it as a cookbook recipe!

Also thanks to all the other responders... It's been highly
educational, especially the part about cool cats not caring about
their own names. (-;

regards,

Sandy

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


"Jason Orendorff" wrote:
> 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.



More information about the Python-list mailing list