Printing variable names
Scott David Daniels
Scott.Daniels at Acm.Org
Sun Jan 18 18:25:40 EST 2004
Mark McEahern wrote:
> Mike wrote:
>> mylist = [a, b, c]
>>
>> I want to print out the names of the variables in mylist (not the
>> values of a, b, and c). How do I go about doing this. Thanks.
>> Mike
> ... One idea is to use a dictionary instead. Then:
> for key, value in mydict.iteritems():
> print '%(key)s = %(value)s' % locals()
> I'm curious what problem you're trying to solve.
Mark's questions are very much on target. If the purpose is debugging,
you might be satisfied with something like:
def vnames(value, *dicts):
"""From a value and some dictionaries and give names for the
value"""
result = []
for d in dicts:
result.extend([key for key, val in d.iteritems()
if val is value])
result.append(repr(value))
return result
Which you might use like:
a,b,c = 1,2,3
d,e,f = 5,4,3
for v in range(10):
print v, vnames(v, locals(), globals())
Note: You probably need only locals or globals if you are at the top
level of an interpreter such as Idle or the python shell.
You might prefer '==' to 'is', but remember that 0.0 == 0 == 0L.
-Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list