OTZ
OTZ

Reputation: 3083

Any way to stringify a variable id / symbol in 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?

Upvotes: 3

Views: 4107

Answers (3)

OTZ
OTZ

Reputation: 3083

"Not possible" is the answer.

Upvotes: -1

Tarantula
Tarantula

Reputation: 19912

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

Upvotes: 4

unbeli
unbeli

Reputation: 30248

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

Upvotes: 3

Related Questions