Getting current variable name

Jeff Shannon jeffshannon at gmail.com
Thu Mar 17 12:32:55 EST 2005


Ron wrote:

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

Are you sure that you really need that single-element list?

 >>> def getvinfo2(vars, v):
... 	for n in vars.keys():
... 		if vars[n] is v:
... 			return n, v, type(v)
... 		
 >>> getvinfo2(locals(), a)
('a', 1, <type 'int'>)
 >>> getvinfo2(locals(), b)
('b', 2.2999999999999998, <type 'float'>)
 >>>

Now, making that second parameter a list would enable you to do this 
for multiple local names with a single call, but getvinfo() doesn't 
try to do that...

Don't forget, in Python, all names are references.  You only have to 
be careful when you start re-binding names...

Jeff Shannon




More information about the Python-list mailing list