allenfrostline

How to Get Variable Name as a String in Python


2019-04-23

Although it’s not recomended, people sometimes need the variable names. For example, you want to automate the process of generating a dictionary with variable names as keys, or use variable names as columns names in a pandas dataframe. How are we gonna implement this in Python?

There is a nasty workaround provided somewhere on Stackoverflow (sorry but I forgot the actual thread):

def varName(p):
    for k, v in globals().items():
        if id(p) == id(v):
            return k


foo = 'well'
far = 12345
print(varName(foo))
print(varName(far))
print(varName(varName))
foo
far
varName

The method utilized the fact that Python stores all variables in the global() dictionary where keys are corresponding id values. Enjoy coding 🙃