how can I get the name of a variable (or other object)?

Cameron Laird claird at lairds.us
Thu Jul 22 10:05:20 EDT 2004


In article <10fvcrk7hmjob60 at news.supernews.com>,
John Roth <newsgroups at jhrothjr.com> wrote:
>
>"Josef Dalcolmo" <dalcolmo at vh-s.de> wrote in message
>news:20040722142305.0000373a at titan...
>> If I have a Python variable like
>>
>> var = 33
>>
>> can I get the name 'var' as a string?
>>
>> Obviously this does not make much sense when using a single variable, but
>if I want to print the variable together with it's name, for a list of
>variables, then it could make sense:
>>
>> def printvariables(varlist):
>> ....for var in varlist:
>> ........print var.__name__, var
>>
>> of course the attribute __name__ I just made up, and if this would always
>return 'var' it would not make any sense either.
>>
>> I am not sure if such a thing is at all possible in Python.
>
>As a general rule, the answer is no. The basic reason is
>that there is a many-to-one relationship between the
>names to which an object is bound, and the object itself.
>In your example, the integer '33' could be bound to a
>large number of different identifiers in different objects.
>
>Python doesn't maintain that kind of a crossreference,
>and even if it did, you'd still need to figure out the
>context you were asking about.
>
>If you know the context, you might consider
>building an inverse dictionary so you can use
>it to look up the object and find the name(s)
>that it's bound to in that context. Timing is
>important here!
			.
			.
			.
While I, too, suspect Mr. Dalcolmo will eventually find
contentment in some sort of use of dictionaries that
address his *real* issue--which we don't yet know, of
course--I wonder if 
  print "The globals are %s, and locals are %s." % (globals(), locals())
will end up pertinent to his needs.



More information about the Python-list mailing list