Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve a variable's name in python at runtime?

Tags:

python

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.)

like image 615
Berry Tsakala Avatar asked May 31 '09 20:05

Berry Tsakala


People also ask

How do you retrieve a variable in Python?

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.

Where are variable names stored in Python?

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.

How do you print variable names?

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[] .


2 Answers

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.)

like image 165
Michael Kuhn Avatar answered Sep 20 '22 12:09

Michael Kuhn


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 .

like image 28
Alex Martelli Avatar answered Sep 22 '22 12:09

Alex Martelli