How to get a variable name as a string in Python?

PythonServer Side ProgrammingProgramming

This isn't really something you do in Python as variables are actually name mappings to objects. The only objects in Python that have canonical names are modules, functions, and classes, and of course there is no guarantee that this canonical name has any meaning in any namespace after the function or class has been defined or the module imported. These names can also be modified after the objects are created so they may not always be particularly trustworthy.

There are still ways to get the name of a variable as string. You need to know the string of the variable name to extract it though. Also this is a reverse search for the variable name. Soif you have 2 variables having the same value, it might return either of them. The iteritems returns the list of all variables in the scope with their values. For example,

>>> my_var = 5
>>> my_var_name = [ k for k,v in locals().iteritems() if v == my_var][0]
>>> my_var_name
Updated on 30-Sep-2019 07:03:06