Search This Blog

Saturday, April 27, 2013

How to find list variable name

I've found an interesting limitation or maybe this is my lack of knowledge about python. I was trying to write a function that takes a list as an argument and prints on stdout  the name of the list and its value. Unfortunately this wasn't possible as there isn't an available function neither from python builtin set or from the list object itself that retrieves the name of a list variable.
 
def example(mylist):
    try:
        print("The argument name %s and value %s" % (mylist.name, mylist))
    except Exception, e:
        print e
    try:
        print("The argument name %s and value %s" % (mylist.__name__, mylist))
    except Exception, e:
        print e    

Trying to run this generate these exceptions:
 
mylist=[1,2]
example(mylist)
'list' object has no attribute 'name'
'list' object has no attribute '__name__'

To solve this problem I write this little auxiliary function that iterates over all global symbols and try to find the variable name base on the value. Unfortunately it isn't perfect as list can have multiple references that share the save value so our function will return all variable names instead of only one.
 
def object_name(obj, ret=None):
    g=globals()
    ret=[]
    obj_id=id(obj)
    for i in g.keys() :
        if id(g[i]) == obj_id :
            print i, g[i]
            ret.append(i)
    return ret

# an example from ipython showing how the code works 
In [47]: l=[1,2,3]
In [48]: a=l 
In [49]: object_name(l)
l [1, 2, 3]
a [1, 2, 3]
Out[49]: ['l', 'a']

References
  1. http://bytes.com/topic/python/answers/854009-how-get-name-list


No comments:

Post a Comment