Printing the name of a variable

Jonathan Hartley tartley at tartley.com
Fri Sep 10 06:13:31 EDT 2010


On Sep 9, 9:11 pm, Albert Hopkins <mar... at letterboxes.org> wrote:
> 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.

I have in the past wondered about creating a kind of graphical
debugger, that rendered representations of all the objects in globals
and/or locals, to give you a visual representation of your variables
and their states. Would this be a valid use case to try and look up
the variable names which reference various in-memory objects?



More information about the Python-list mailing list