Getting name of a variable in Python
Question:
If I have local/global variable var
of any type how do I get its name, i.e. string "var"
? I.e. for some imaginary function or operator nameof()
next code should work:
var = 123
assert nameof(var) == "var"
There’s .__name__
property for getting name of a function or a type object that variable holds value of, but is there anything like this for getting name of a variable itself?
Can this be achieved without wrapping a variable into some magic object, as some libraries do in order to get variable’s name? If not possible to achieve without magic wrappers then what is the most common/popular wrapping library used for this case?
Answers:
You can do this with the package python-varname: https://github.com/pwwang/python-varname
First run pip install varname
. Then see the code below:
from varname import nameof
var = 123
name = nameof(var)
#name will be 'var'
For Python 3.8 and later, you can try this not-so-pretty way, but it works for any python object that has a str-method:
var = 123
var_name = f'{var=}'.partition('=')[0]
def get_veriable_name(variable):
current_file = os.path.basename(__file__)
with open(current_file, "r") as f:
for line in f:
if variable in line:
return line.split("=")[0].strip()
return None
If I have local/global variable var
of any type how do I get its name, i.e. string "var"
? I.e. for some imaginary function or operator nameof()
next code should work:
var = 123
assert nameof(var) == "var"
There’s .__name__
property for getting name of a function or a type object that variable holds value of, but is there anything like this for getting name of a variable itself?
Can this be achieved without wrapping a variable into some magic object, as some libraries do in order to get variable’s name? If not possible to achieve without magic wrappers then what is the most common/popular wrapping library used for this case?
You can do this with the package python-varname: https://github.com/pwwang/python-varname
First run pip install varname
. Then see the code below:
from varname import nameof
var = 123
name = nameof(var)
#name will be 'var'
For Python 3.8 and later, you can try this not-so-pretty way, but it works for any python object that has a str-method:
var = 123
var_name = f'{var=}'.partition('=')[0]
def get_veriable_name(variable):
current_file = os.path.basename(__file__)
with open(current_file, "r") as f:
for line in f:
if variable in line:
return line.split("=")[0].strip()
return None