How to turn a variable name into a string?
Lonnie Princehouse
finite.automaton at gmail.com
Fri Mar 11 14:25:03 EST 2005
Any given Python object may be bound to multiple names or none at all,
so trying to find the symbol(s) which reference an object is sort of
quixotic.
In fact, you've got None referenced by both "my" and "c" in this
example, and in a more complicated program None will be referenced by
dozens symbols because it's unique [e.g. (a == None, b == None)
necessitates (a is b) == True]
You could try using "is" to match it with something in the namespace,
though. This might do what you want.
def names(thing):
return [name for name,ref in globals().iteritems() if ref is thing]
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' % names(my)
-------------
Although it would be much simpler to rewrite your code like this:
a = 1; b = 2; c = None
mylist = ['a','b','c']
for my_name in mylist:
my = eval(my_name)
if my is None:
print 'you have a problem with %s' % my_name
More information about the Python-list
mailing list