How to get the 'name' of an int

Alex Martelli aleax at aleax.it
Sat Mar 1 02:17:45 EST 2003


Charl P. Botha wrote:

>> "Hans Brand" <Hans.Brand at BrandInnovators.com> wrote in message
>> news:b3najo$hej$1 at reader08.wxs.nl...
>>> 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).


Alex





More information about the Python-list mailing list