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

Duncan Booth me at privacy.net
Thu Jul 22 08:55:57 EDT 2004


Josef Dalcolmo <dalcolmo at vh-s.de> wrote in
news:20040722142305.0000373a at titan: 

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

>>> var = 33
>>> import sys
>>> print sys.getrefcount(33)
11
>>> 

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.



More information about the Python-list mailing list