getting the name of a variable

Daniel Klein danielk at aracnet.com
Thu Dec 6 09:33:42 EST 2001


Forgot to mention, if var cannot be found in the globals() dicitonary,
it will throw a KeyError exception. A slight modification to the
function will handle this

>>> def varname(var):
	var = str(var)
	try:
		print var + " : " + str(globals()[var])
	except KeyError:
		print var + " : <undefined>"
	
>>> varname('zz')
zz : <undefined>

Dan

On Thu, 06 Dec 2001 06:03:11 -0800, Daniel Klein <danielk at aracnet.com>
wrote:

>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