getting the name of a variable

Hans Nowak wurmy at earthlink.net
Thu Dec 6 11:35:19 EST 2001


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.

I don't think "variables" have a notion of their name; essentially
they are objects floating somewhere in memory, with a name (or
multiple names) in a namespace referring to them.

Some objects do have a __name__ attribute, like classes, but even
this doesn't always return the desired result:

>>> class Foo: pass

>>> Bar = Foo
>>> Bar.__name__
'Foo'  # instead of "Bar"

Aside from that, objects can have multiple names bound to them,
all of which are equally valid:

>>> l = range(10)
>>> m = n = l

In other words, the list object doesn't keep track of all the
names referring to it... therefore it cannot "know" what its name
is, and even if it did keep track, there is not just one name.

You can do some trickery with globals(), like Daniel Klein did,
but this only works for the global namespace; you're out of luck
when you want to use this debugging construct inside a function.

--Hans



More information about the Python-list mailing list