tags:

views:

163

answers:

3

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?

+3  A: 

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
unbeli
+4  A: 

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

Tarantula
>>> symbol_name(a)'a'>>> b=a>>> symbol_name(b)'a'oops
unbeli
Given that any object can have multiple names, wouldn't this be slightly better: if a is v: results.append(k) ... (assuming you wrap the loop in an instantiation and return of "results").
Jim Dennis
but, good idea anyway :)
unbeli
I used locals() instead of globals(), now is working.
Tarantula
still cannot tell the difference between two equal variables. Obviously, if id(x)==id(y), then symbol_name(x) == symbol_name(y), but should be 'x' != 'y'
unbeli
Are you trying to provide debugging information? Might you consider using the traceback module? If you're trying to report "the name" of an object you might have to search through locals() and globals() and ... I'm not sure sure what other name spaces.
Jim Dennis
unbeli is right, it works not for all cases, if two variables have the same id, it may return the wrong name.
Tarantula
symbol_name(non_existent) yields a traceback with "NameError: name 'non_existent' is not defined" message so that NameError gets the right "name". Couldn't we use the same logic? How and where does NameError gets the "name"?
OTZ
A: 

"Not possible" is the answer.

OTZ