Search code examples
pythonvariables

Getting name of a variable in Python


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?


Solution

  • 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'