Printing a variable's name not its value

tiissa tiissa at nonfree.fr
Wed Jul 20 22:39:30 CEST 2005


Simon Dahlbacka wrote:
> as you have been told, there is no way to get a variable's name

Well, if you really want to, you can get all the names bound to a given 
object:


def get_names(obj):
     g = globals()
     names = []
     for name in g:
         if g[name] is obj:
             names.append(name)
     return names


Then you can play around:

  >>> list1 = []
  >>> list2 = [list1]
  >>> get_names(list2)
  ['list2']
  >>> list3 = list2
  >>> get_names(list2)
  ['list3', 'list2']
  >>> get_names(1)
  []
  >>> a = 1
  >>> get_names(1)
  ['a']
  >>> b = 1
  >>> get_names(1)
  ['a', 'b']
  >>> get_names(a)
  ['a', 'b']
  >>> c = 4/3.
  >>> d = 4/3.
  >>> get_names(c)
  ['c']
  >>> get_names(d)
  ['d']
  >>> get_names(4/3.)
  []
  >>>


But I wouldn't do it. If I want a name to be attached to some objects, I 
usually include it as a member/property of my class.



More information about the Python-list mailing list