tags:

views:

1145

answers:

4

is there a way to know, during run-time, a variable's name (from the code) ? or do var names forgotten during compilation (byte-code or not) ?

e.g.

>>>  vari = 15
>>>  print vari.~~name~~()
'vari'

note: i'm talking about plain data-type variables (int, str, list...)

+5  A: 

Variable names persist in the compiled code (that's how e.g. the dir built-in can work), but the mapping that's there goes from name to value, not vice versa. So if there are several variables all worth, for example, 23, there's no way to tell them from each other base only on the value 23 .

Alex Martelli
+8  A: 

Variable names don't get forgotten, you can access variables (and look which variables you have) by introspection, e.g.

>>> i = 1
>>> locals()["i"]
1

However, because there are no pointers in Python, there's no way to reference a variable without actually writing its name. So if you wanted to print a variable name and its value, you could go via locals() or a similar function. ([i] becomes [1] and there's no way to retrieve the information that the 1 actually came from i.)

biocs
this solves my case. then i make reverse lookup on their values, and find their names. thanks.
Berry Tsakala
The hard part about this is that if you only have `i' then it is impossible to find it's name in `locals()`. Consider 'i=1; j=1;'. After this 'locals()["i"] is locals()["j"]'. If all that you have is `i' then looping through locals() will result in finding either `i' or `j' as the name.
D.Shawley
D. probably intended to say "If all that you have is `1` [...]"
akaihola
A: 

Just yesterday I saw a blog post with working code that does just this. Here's the link:

http://pyside.blogspot.com/2009/05/finding-objects-names.html

piquadrat
A: 

I tried the following link from the post above with no success: Googling returned this one.

http://pythonic.pocoo.org/2009/5/30/finding-objects-names