Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting name of a variable in Python [duplicate]

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?

like image 513
Arty Avatar asked Dec 22 '25 02:12

Arty


1 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'
like image 152
Fried Noodles Avatar answered Dec 23 '25 21:12

Fried Noodles