Printing the name of a variable

Paul Rudin paul.nospam at rudin.co.uk
Fri Sep 10 09:13:33 CEST 2010


Stephen Boulet <stephen.boulet at gmail.com> writes:

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

The first thing is... what is your use case for this? I'd guess that you
probably don't want to do this even if you think you do :)

The thing referred to by x is the number 10. When you write x.name (or
property) then you're dealing with the number 10, not with some
representation of the variable x. There may be many variables (or none)
that refer to that number at any given time during the execution of your
code... and the object itself "knows" nothing about any of these.

A good way to think about variable lookup is as a dictionary . It's
something like "variables['x'].name". Once the "varables['x'] bit has
been evaluated the link with 'x' is gone... we just have the result of
the lookup.

If you want to know how it actually works, then read up on python
namespaces and scopes, e.g. here:
<http://www.network-theory.co.uk/docs/pytut/PythonScopesandNameSpaces.html>.



More information about the Python-list mailing list