e-satis e-satis - 1 month ago 6x
Python Question

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

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__)

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
, so I guess there is a way.


Are you trying to do this?

dict( (name,eval(name)) for name in ['some','list','of','vars'] )


>>> some= 1
>>> list= 2
>>> of= 3
>>> vars= 4
>>> dict( (name,eval(name)) for name in ['some','list','of','vars'] )
{'list': 2, 'some': 1, 'vars': 4, 'of': 3}