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?

Asked By: Arty

||

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'
Answered By: Fried Noodles

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]
Answered By: Sum Zbrod
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
Answered By: Sifat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.