getting the name of a variable

Mark Jackson mjackson at wrc.xerox.com
Thu Dec 6 10:26:59 EST 2001


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

Daniel Klein <danielk at aracnet.com> writes:

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

That's not what Daniel wanted; he was looking for this behavior:

>>> a = 'spam'
>>> varname(a)
a : spam
>>>

You *can* write a function to search the embedding namespace for an
object match (using is, not ==) and get this behavior. . .sometimes.
The problem is that the object may have more than one name

>>> a = 'spam'
>>> b = a
>>> varname(a)
one spam or another
>>>

or none at all

>>> a = ['eggs','spam']
>>> varname(a[1])
the spam that dare not speak its name
>>>

-- 
Mark Jackson - http://www.alumni.caltech.edu/~mjackson
	This is a clear abuse of the God-given gifts
	of repression and denial.
			- The Reverend Theo Fobius (Howard Tayler)





More information about the Python-list mailing list