How to get the 'name' of an int

Alex Martelli aleax at
Sat Mar 1 08:17:45 CET 2003

Charl P. Botha wrote:

>> "Hans Brand" <Hans.Brand at> wrote in message
>> news:b3najo$hej$1 at
>>> Hi,
>>> I would like to get the 'name' of a variable to do something like this:
>>> causea = 12
>>> causeb = 13
>>> for cause in (causea, causeb):
>>>     print "%s = %s" %(name(cause), cause)
> To find the name of the variable, you could also try something like:
> [i[0] for i in locals().items() if i[1] is causea][0]
> which will yield the string 'causea' if you've bound causea as above.

Yes, but try it when two variables have the same value, e..g:

causea = 12
causeb = 13
causec = 12

and you'll see it break for one of them.  (Same value -> one that
satisfies your 'is' test, but small integers do satisfy it, as
Python keeps only one copy of each of them, not seevral ones).


More information about the Python-list mailing list