How to turn a variable name into a string?

Peter Hansen peter at engcorp.com
Fri Mar 11 14:15:54 EST 2005


Stewart Midwinter wrote:
> I'd like to do something like the following:
> 
> a = 1; b = 2; c = None
> mylist = [a, b, c]
> for my in mylist:
>     if my is None:
>     print 'you have a problem with %s' % my         #this line is problematic
> 
>>>>You have a problem with None
> 
> What I want to see in the output is:
>>>>You have a problem with c
> 
> How do I convert a variable name into a string?

You cannot.  In the above example, when you hit
the None item in the list, there is only one None
object in existence, and three different names
"bound" to it: c, my, and the third spot in the
list.  (Think of this "bound" thing as being like
strings attaching a variety of names to the item
itself.)

Given the object "None" then, how can Python know
which of the names you intended?  More to the
point, by the time you've finished creating the
list mylist, the connection to "c" is long gone.
It is exactly as though you had typed this instead:
   mylist = [1, 2, None]

There are doubtless other ways to accomplish what
you are really trying to do (display some sort of
information for debugging purposes?), but with a
contrived example it's a little hard to pick the
best...

By the way, this sort of thing should be well
covered by the FAQ entries, if you read them.
See, for example, 
http://www.python.org/doc/faq/programming.html#how-can-my-code-discover-the-name-of-an-object

-Peter



More information about the Python-list mailing list