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


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 .


Here is a function I use to print the value of variables, it works for local as well as globals:

import sys
def print_var(var_name):
    calling_frame = sys._getframe().f_back
    var_val = calling_frame.f_locals.get(var_name, calling_frame.f_globals.get(var_name, None))
    print (var_name+':', str(var_val))

So the following code:

global_var = 123
def some_func():
    local_var = 456
    print_var("global_var")
    print_var("local_var")
    print_var("some_func")

some_func()

produces:

global_var: 123
local_var: 456
some_func: <function some_func at 0x10065b488>

Tags:

Python