getting name of passed reference

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Mon Dec 28 20:28:51 EST 2009


On Mon, 28 Dec 2009 15:54:04 -0800, Joel Davis wrote:

> I'm just curious if anyone knows of a way to get the variable name of a
> reference passed to the function.
> 
> Put another way, in the example:
> 
>   def MyFunc ( varPassed ):
>      print varPassed;
> 
>   MyFunc(nwVar)
> 
> how would I get the string "nwVar" from inside of "MyFunc"? is it
> possible?

Not via standard Python. There are a few ways of guessing a possible name 
using frames, but:

(1) all such solutions are nasty hacks;
(2) some of them require the source code to be available, which isn't 
always the case;
(3) they almost certainly won't be portable to other Python 
implementations; 
(4) they're probably expensive and relatively slow; and
(5) not all objects have a name, and some objects have multiple names.


For example, here's one way to get a list of all the names that an object 
is known as (if any):


def get_names(obj, level=1):
    # WARNING: this uses implementation-specific Python private details
    frame = sys._getframe(level)
    return [k for (k, v) in frame.f_locals.items() if v is obj]


And here's an example of it in use:

>>> var = 'foo'
>>> c = 'foo'
>>> get_names('foo')
['c', 'var']
>>> get_names(25)
[]
>>> def test(x):
...     print get_names(x, 2)
...
>>> test(var)
['c', 'var']



Notice that, in general, there's NO WAY to tell from inside test that the 
string was passed using the name 'var' rather than the name 'c'.



Why do you want to do such a thing?



-- 
Steven



More information about the Python-list mailing list