Retrieving a variable's name.

James Stroud jstroud at
Tue Aug 21 06:00:05 CEST 2007

rodrigo wrote:
> How would I go about retrieving a variable's name (not its value)? I
> want to write a function that, given a list of variables, returns  a
> string with each variable's name and its value, like:
> a: 100
> b: 200
> I get the feeling this is trivial, but I have been unable to find an
> answer on my own.
> Thanks,
> Rodrigo

Use a dict as that is what you access when you use namespaces anyway:

py> type(globals())
<type 'dict'>

The essential problem with what you suggest is that python assigns names 
to references to objects, so the interpreter can not tell what name you 
want by a reference to the object, so it gives you whatever name it 
happens to find, which, since the names are keys to a dict, come in 
arbitrary order. For example, consider this situation:

py> a = 4
py> b = a
py> ns = globals()
py> for avar in a,b:
...   for k,v in ns.items():
...     if v is avar:
...       print '%s is %s' % (k,v)
...       break
avar is 4
avar is 4

So getting at the names by reference to thee objects will never be 
dependable. Passing names makes more sense:

py> for aname in ['a', 'b']:
...   print '%s is %s' % (aname, globals()[aname])
a is 4
b is 4

But this is tantamount to using a dict:

py> mydict = {'a':4, 'b':2}
py> for aname in ['a', 'b']:
...   print '%s is %s' % (aname, mydict[aname])
a is 4
b is 2

Which is preferred because it keeps your namespaces cleaner.


James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

More information about the Python-list mailing list