Printing the name of a variable

S

Stephen Boulet

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
Perhaps the x.__getattribute__ method? Thanks.
 
A

Albert Hopkins

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

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

Mel

Stephen said:
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

Perhaps the x.__getattribute__ method? Thanks.

Hmm. "Recent scholarship suggests that the Iliad and the Odyssey may not
have been written by Homer, but by someone else with the same name."

Mel.
 
P

Paul Rudin

Stephen Boulet said:
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

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,169
Messages
2,570,920
Members
47,463
Latest member
FinleyMoye

Latest Threads

Top