e-satis e-satis - 1 year ago 153
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.

Answer Source

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}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download