Getting the name of a variable as a string

This thread discusses how to get the name of a function as a string in Python: How to get a function name as a string in Python?

How can I do the same for a variable? (note that Python variables do not have the attribute __name__, at least in Python 2.7.x)

In other words, if I have a variable such as:

    foo = dict()
    foo['bar'] = 2

I am looking for a function/attribute, e.g. retrieve_name:


that returns the string 'foo'


Since people are asking why I want to do this, here is an example. I would like to create a DataFrame in Pandas from this list, where the column names are given by the names of the actual dictionaries:

    # List of dictionaries for my DataFrame
    list_of_dicts = [n_jobs, users, queues, priorities]

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.

What you want to do is not possible without recursively walking the tree of named objects; a name is a one-way reference to an object. A common or garden-variety Python object contains no references to its names. Imagine if every integer, every dict, every list, every Boolean needed to maintain a list of strings that represented names that referred to it! It would be an implementation nightmare, with little benefit to the programmer.


Back to homepage or read more recommendations: