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
'my_var'
raja
Published on 13-Dec-2017 08:48:41
Advertisements