Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to stringify a variable id / symbol in Python?

Tags:

python

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?

like image 874
OTZ Avatar asked Dec 04 '25 19:12

OTZ


2 Answers

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

like image 127
Tarantula Avatar answered Dec 06 '25 08:12

Tarantula


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
like image 42
unbeli Avatar answered Dec 06 '25 08:12

unbeli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!