how can I get the name of a variable (or other object)?

J

Josef Dalcolmo

If I have a Python variable like

var = 33

can I get the name 'var' as a string?

Obviously this does not make much sense when using a single variable, but if I want to print the variable together with it's name, for a list of variables, then it could make sense:

def printvariables(varlist):
.....for var in varlist:
.........print var.__name__, var

of course the attribute __name__ I just made up, and if this would always return 'var' it would not make any sense either.

I am not sure if such a thing is at all possible in Python.

Best regards - Josef Dalcolmo
 
J

John Roth

Josef Dalcolmo said:
If I have a Python variable like

var = 33

can I get the name 'var' as a string?

Obviously this does not make much sense when using a single variable, but
if I want to print the variable together with it's name, for a list of
variables, then it could make sense:
def printvariables(varlist):
....for var in varlist:
........print var.__name__, var

of course the attribute __name__ I just made up, and if this would always
return 'var' it would not make any sense either.
I am not sure if such a thing is at all possible in Python.

As a general rule, the answer is no. The basic reason is
that there is a many-to-one relationship between the
names to which an object is bound, and the object itself.
In your example, the integer '33' could be bound to a
large number of different identifiers in different objects.

Python doesn't maintain that kind of a crossreference,
and even if it did, you'd still need to figure out the
context you were asking about.

If you know the context, you might consider
building an inverse dictionary so you can use
it to look up the object and find the name(s)
that it's bound to in that context. Timing is
important here!

John Roth
 
D

Duncan Booth

If I have a Python variable like

var = 33

can I get the name 'var' as a string?
Obviously this does not make much sense when using a single variable,
but if I want to print the variable together with it's name, for a
list of variables, then it could make sense:

def printvariables(varlist):
....for var in varlist:
........print var.__name__, var

of course the attribute __name__ I just made up, and if this would
always return 'var' it would not make any sense either.

I am not sure if such a thing is at all possible in Python.
I think you would do well to read http://www.effbot.org/zone/python-
objects.htm

When you read this you should soon see that your question isn't really
meaningful: Python doesn't have variables; it has objects, names and
bindings.

Try this:

The value 33 which I bound to the name 'var', also has another 10
references. Some of these may be names in other namespaces, and others are
completely anonymous (the parameter to sys.getrefcount is one of them), but
they are all the same object: an integer with the value 33.
 
C

Cameron Laird

if I want to print the variable together with it's name, for a list of
variables, then it could make sense:
return 'var' it would not make any sense either.

As a general rule, the answer is no. The basic reason is
that there is a many-to-one relationship between the
names to which an object is bound, and the object itself.
In your example, the integer '33' could be bound to a
large number of different identifiers in different objects.

Python doesn't maintain that kind of a crossreference,
and even if it did, you'd still need to figure out the
context you were asking about.

If you know the context, you might consider
building an inverse dictionary so you can use
it to look up the object and find the name(s)
that it's bound to in that context. Timing is
important here!
.
.
.
While I, too, suspect Mr. Dalcolmo will eventually find
contentment in some sort of use of dictionaries that
address his *real* issue--which we don't yet know, of
course--I wonder if
print "The globals are %s, and locals are %s." % (globals(), locals())
will end up pertinent to his needs.
 
R

Richard Oudkerk

Try

def printvars(varlist):
allvars = globals()
allvars.update(locals())
for var in varlist:
print [ n for n in allvars if allvars[n] is var ], "=>", var

a = 10
b = 20
c = 30
d = a
e = "hello"

printvars([a,b,e, 143, printvars, None])

It gives the output

['a', 'd'] => 10
['b'] => 20
['e'] => hello
[] => 143
['printvars'] => <function printvars at 0xa0c53e4>
['__doc__'] => None

Richard

Josef said:
> If I have a Python variable like
>
> var = 33
>
> can I get the name 'var' as a string?
>
> Obviously this does not make much sense when using a single variable, but if
I want to print the variable together with it's name, for a list of variables,
then it could make sense:
>
> def printvariables(varlist):
> ....for var in varlist:
> ........print var.__name__, var
>
> of course the attribute __name__ I just made up, and if this would always
return 'var' it would not make any sense either.
 
G

Grant Edwards

If I have a Python variable like

var = 33

can I get the name 'var' as a string?

Obviously this does not make much sense when using a single
variable, but if I want to print the variable together with
it's name, for a list of variables, then it could make sense:

Python doesn't have variables. Python has objects. Python has
dictionaries that map strings (names) to objects. In your
example above, there is an integer object with a value of 33.

In your locals or globals dictionary you have placed an entry
with the key 'var' which points to the integer object with the
value 33. The object doesn't actually have a name. There may
be many dictionary entries with diffferent "names" that all
point to the same integer object.
def printvariables(varlist):
....for var in varlist:
........print var.__name__, var

of course the attribute __name__ I just made up, and if this
would always return 'var' it would not make any sense either.

I am not sure if such a thing is at all possible in Python.

What I suspect you're trying to do is something like the code
shown below. How does one obtain a reference to the locals
dictionary for one's calling function?


def printvariables(varlist):
g = globals()
for v in varlist:
if v in g:
print "%s = %s %s" % (v,type(g[v]),g[v],)
else:
# we should try to look up v in the locals for the
# caller, but I don't remember how to get that.
print "%s undefined" % v


if __name__ == '__main__':
x = 1
y = 2.3
z = 'howdy'
d = {x:y, z:7.8}

printvariables(['x','y','z','d'])
 
G

Grant Edwards

Try

def printvars(varlist):
allvars = globals()
allvars.update(locals())
for var in varlist:
print [ n for n in allvars if allvars[n] is var ], "=>", var

I don't think the allvars.update(locals()) is doing anything
useful. The locals it's adding are those belonging to
'printvars' and what one would probably want is the locals
belonging to the caller of printvar.

I like your solution of passing objects better than mine of
passing the name.
 
G

Grant Edwards

Try

def printvars(varlist):
allvars = globals()
allvars.update(locals())
for var in varlist:
print [ n for n in allvars if allvars[n] is var ], "=>", var

I don't think the allvars.update(locals()) is doing anything
useful. The locals it's adding are those belonging to
'printvars' and what one would probably want is the locals
belonging to the caller of printvar.

That would be:

allvars.update(sys._getframe(1).f_locals)

Better yet, print whether the object was found in the globals or
locals .
 
J

JCM

Grant Edwards said:
Python doesn't have variables. Python has objects. Python has
dictionaries that map strings (names) to objects. In your
example above, there is an integer object with a value of 33.

The Python documentation talks about variables. Personally I think
that's a fine name for the scoped binding between an identifier and a
value.
 
G

Grant Edwards

The Python documentation talks about variables. Personally I
think that's a fine name for the scoped binding between an
identifier and a value.

But it's not a binding between an identifier and a value. It's
a binding between an identifier and an _object_. For immutable
objects, it's a moot point, but for mutable objects, there are
some real-world programming consequences.

I think it's very confusing to people who were taught that a
variable is a named region of storage in which a value
(possibley of one specific type) could be stored. I think that
referring to a Python name/object pair as "a variable" is
perpetuating a fundamental misunderstanding of what's really
going on.

If we want to refer to Python "variables" then I think the
"value" of a "variable" should be always be referred to as "a
pointer to an object".

I'm probably being overly pedantic, but I've seen a lot of
confusing amongst new Python programs due to their view of
python name bindings as "variables" in the traditional sense of
the word.
 
J

JCM

But it's not a binding between an identifier and a value. It's
a binding between an identifier and an _object_. For immutable
objects, it's a moot point, but for mutable objects, there are
some real-world programming consequences.

I consider the values to be references to objects. But as you say...
I think it's very confusing to people who were taught that a
variable is a named region of storage in which a value
(possibley of one specific type) could be stored. I think that
referring to a Python name/object pair as "a variable" is
perpetuating a fundamental misunderstanding of what's really
going on.
If we want to refer to Python "variables" then I think the
"value" of a "variable" should be always be referred to as "a
pointer to an object".
I'm probably being overly pedantic, but I've seen a lot of
confusing amongst new Python programs due to their view of
python name bindings as "variables" in the traditional sense of
the word.

It's really just about terminology. Personally I'd find it confusing
if I were new to Python and heard someone say that Python has
bindings-of-some-sort, but not variables. My background is compilers
and programming language semantics, so maybe I'm also just being
overly pedantic.
 
G

Grant Edwards

I consider the values to be references to objects. But as you say...

Exactly. As long as variables' values are always talked about
as "pointers to objects" or "references to ojbects", then the
term 'variable' has the traditional meaning.
 

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
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top