I'm wondering if it is possible at all in python to stringify variable id/symbol -- that is, a function that behaves as follows:
>>> symbol = 'whatever'
>>> symbol_name(symbol)
'symbol'
Now, it is easy to do it on a function or a class (if it is a direct reference to the object):
>>> def fn(): pass
>>> fn.func_name
'fn'
But I'm looking for a general method that works on all cases, even for indirect object references. I've thought of somehow using id(var), but no luck yet.
Is there any way to do it?
Here is, I'm sure you can turn it into a better form =)
def symbol_name(a):
for k,v in globals().items():
if id(a)==id(v): return k
Update: As unbeli has noted, if you have:
a = []
b = a
The function will not be able to show you the right name, since id(a)==id(b).
I don't think it's possible. Even for functions, that is not the variable name:
>>> def fn(): pass
...
>>> fn.func_name
'fn'
>>> b=fn
>>> b.func_name
'fn'
>>> del fn
>>> b.func_name
'fn'
>>> b()
>>> fn()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'fn' is not defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With