getting the name of a variable

Daniel Klein danielk at aracnet.com
Thu Dec 6 09:03:11 EST 2001


Assuming the variable is user-defined (not in __builtins__) and is not
local to the function/method...

>>> x = 42
>>> y = ['a','b','c']
>>> def varname(var):
	print str(var) + " : " + str(globals()[var])

>>> varname('x')
x : 42
>>> varname('y')
y : ['a', 'b', 'c']
>>> 

Daniel Klein


On 6 Dec 2001 04:47:37 -0800, sandskyfly at hotmail.com (Sandy Norton)
wrote:

>When I'm debugging I'm always sticking stuff like "print 'x:', x" in my code.
>So is there a handy function that will print a variable name and value such that: 
>
>>>> def print_var_name_and_value(var):
>            "prints variable name : value"
>            <implemention>
>
>>>> variable = 'me var'
>>>> print_var_name_and_value(variable)
>variable : me var
>
>
>Any responses, pointers, hints would be much appreciated.
>
>thanx.
>
>Sandy





More information about the Python-list mailing list