Printing the name of a variable

Albert Hopkins marduk at letterboxes.org
Thu Sep 9 22:11:27 CEST 2010


On Thu, 2010-09-09 at 12:43 -0700, Stephen Boulet wrote:
> Does an arbitrary variable carry an attribute describing the text in
> its name? I'm looking for something along the lines of:
> 
> x = 10
> print x.name
> >>> 'x'
> 
> Perhaps the x.__getattribute__ method? Thanks.

Variables are not objects and so they have no attributes.

You can't really de-reference the object being referenced as it can
potentially contain multiple references, but an innacurate way of doing
this would be, e.g.

>>> x = [1, 2, 3]
>>> y = x
>>> g = globals() 
>>> varnames = [i for i in g if g[i] is x]
['x', 'y']

But this cries the question: why do you want to do this?  And usually
that question is asked when someone thinks that a: you shouldn't need to
do this and b: whatever the desired effect there is probably a better
way of accomplishing it.




More information about the Python-list mailing list