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
:
retrieve_name(foo)
that returns the string 'foo'
Update:
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]
For constants, you can use an enum, which supports retrieving its name.
I wrote the package sorcery to do this kind of magic robustly. You can write:
and pass that to the dataframe constructor. It's equivalent to:
I think it's so difficult to do this in Python because of the simple fact that you never will not know the name of the variable you're using. So, in his example, you could do:
Instead of:
I try to get name from inspect locals, but it cann't process var likes a[1], b.val. After it, I got a new idea --- get var name from the code, and I try it succ! code like below:
On python3, this function will get the outer most name in the stack:
It is useful anywhere on the code. Traverses the reversed stack looking for the first match.
Here's one approach. I wouldn't recommend this for anything important, because it'll be quite brittle. But it can be done.
Create a function that uses the
inspect
module to find the source code that called it. Then you can parse the source code to identify the variable names that you want to retrieve. For example, here's a function calledautodict
that takes a list of variables and returns a dictionary mapping variable names to their values. E.g.:Would give:
Inspecting the source code itself is better than searching through the
locals()
orglobals()
because the latter approach doesn't tell you which of the variables are the ones you want.At any rate, here's the code:
The action happens in the line with
inspect.getouterframes
, which returns the string within the code that calledautodict
.The obvious downside to this sort of magic is that it makes assumptions about how the source code is structured. And of course, it won't work at all if it's run inside the interpreter.