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.:
>>> vari = 15 >>> print vari.~~name~~() 'vari'
Note: I'm talking about plain data-type variables (int
, str
, list
etc.)
To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
This is how it works internally too. In CPython, variable names and the objects they point to are typically stored in a Python dictionary; the very same data structure that you can use when writing Python code.
Print Variable Name With a Dictionary in Python We stored the variable values as keys and the corresponding variable names as the vnames dictionary values. Whenever we have to print the name of a particular variable, we have to pass the value inside vnames[] .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With