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
No comments:
Post a Comment