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

Brian van den Broek bvande at
Tue Mar 29 08:53:54 CEST 2005

stewart.midwinter at said unto the world upon 2005-03-29 01:06:
> No doubt I've overlooked something obvious, but here goes:
> Let's say I assign a value to a var, e.g.:
> myPlace = 'right here'
> myTime  = 'right now'
> Now let's say I want to print out the two vars, along with their names.
> I could easily do this:
> print "myPlace = %s, myTime = %s" % (myPlace, myTime)
> But that requires that I know in advance the name of the vars.  What if
> they are assigned dynamically.  What I'm looking for is some method (
> call it f() ) that allows me to do this:
> print "%s = %s, %s = %s" % (f(myPlace), myPlace, f(myTime), myTime)
> Any ideas?
> repr() doesn't do it for me, nor ``.
> thanks
> Stewart in Calgary

Use a dictionary instead of free floating variables to store your data.

Stewarts_data = { 'myPlace' : 'right here',
                   'myTime' : 'right now' }
for item in Stewarts_data.items():
     print '%s = %s' %item

(There are likely even nicer ways -- for instance in Python 2.4 you 
can use sorted() on the dictionary -- but this gets the idea across, I 


Brian vdB

More information about the Python-list mailing list