I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like:
>>> print(my_var.__name__)
'my_var'
I want to do that because I have a bunch of vars I'd like to turn into a dictionary like :
bar = True
foo = False
>>> my_dict = dict(bar=bar, foo=foo)
>>> print my_dict
{'foo': False, 'bar': True}
But I'd like something more automatic than that.
Python have locals()
and vars()
, so I guess there is a way.
This is a hack. It will not work on all Python implementations distributions (in particular, those that do not have
traceback.extract_stack
.)Note that this hack is fragile:
(calling make_dict on 2 lines) will not work.
Instead of trying to generate the dict out of the values
foo
andbar
, it would be much more Pythonic to generate the dict out of the string variable names'foo'
and'bar'
:This is not possible in Python, which really doesn't have "variables". Python has names, and there can be more than one name for the same object.
With python 2.7 and newer there is also dictionary comprehension which makes it a bit shorter. If possible I would use getattr instead eval (eval is evil) like in the top answer. Self can be any object which has the context your a looking at. It can be an object or locals=locals() etc.
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.
Are you trying to do this?
Example
Here's the function I created to read the variable names. It's more general and can be used in different applications:
To use it in the specified question: