Is there a way to know, during run-time, a variable\'s name (from the code)? Or do variable\'s names forgotten during compilation (byte-code or not)?
e.g.:
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
.)
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
.