Little Q: how to print a variable's name, not its value?

stewart.midwinter at stewart.midwinter at
Thu Mar 31 07:56:06 CEST 2005

my god, I've created a monster!

Maybe I should restate my original problem. Actually, the word
'problem' is too strong. I had a little curiosity about whether I could
write a couple of lines of code more succinctly, or more pythonically.
  I didn't realize that this would trigger a discussion about mixing
data and objects - though I can see the danger if you get into some
situations. Hopefully mine is not one of those.

Restating:  I'm doing some debugging of some code.  I want to print out
the value of two variables whose names are known.  Let's call them
myTime and myPlace.

if self.debug:
   print "myTime = %s, myPlace = %s" % (myTime, myPlace)

Notice that I had to type the variable's name once as an object, and
once as the string representation of that object, i.e. the object's
I wondered whether it might not be possible to do something like this:
if self.debug:
   print "%s = %s" % ( name(myTime), myTime )
where 'name' is the method or trick I'm after.

Creating a dictionary is already more work than it's worth, not to
mention some of the more involved solutions.   I'm left to conclude
that it's not possible to do what I wanted with Python.  If that's the
case, so be it and I'll move on to explore other curiosities.

But surely if you create an integer object and assign it a value, e.g.
a = 3,
why shouldn't Python be able to tell you something like the following:
name(a)  >>> 'a'


More information about the Python-list mailing list