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):

1
2
3
4
5
6
7
8
9
10
11
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 ๐Ÿ™ƒ