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

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

Leave a Comment