How to get a variable name as a string in Python?
Posted
by e-satis
on Stack Overflow
See other posts from Stack Overflow
or by e-satis
Published on 2010-03-31T13:39:10Z
Indexed on
2010/03/31
14:03 UTC
Read the original article
Hit count: 151
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 mydict
>>> 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.
© Stack Overflow or respective owner