Getting current variable name

Ron radam2 at tampabay.rr.com
Thu Mar 17 02:23:14 EST 2005


pl wrote:
> Hi all,
> I followed the mails entitled 'How to turn a variable name into a
> string?' in march 2005 posts as I have a similar problem.

Use the locals() function instead of globals().

Thanks by the way, I was wondering how to do this also, your post, and 
Daniel pointing out 'is', helped me work this out.  There should be an 
easier way that doesn't require stepping though the name list.

This doesn't use lists in the same way, but I think it answers your 
question.

def getvinfo(vars, v):
     """
     vars is locals()
     v is [varable]
     Use an one item list to pass single varables by reference.
     """
     for n in vars.keys():
         if vars[n] is v[0]:
             return n, v[0], type(v[0])

a = 101
b = 2.3
c = True

print getvinfo(locals(), [a])
print getvinfo(locals(), [b])
print getvinfo(locals(), [c])

 >>>
('a', 101, <type 'int'>)
('b', 2.2999999999999998, <type 'float'>)
('c', True, <type 'bool'>)


This could be useful for printing error messages and debugging info.

Ronald Adam



More information about the Python-list mailing list