How to obtain an instance's name at runtime?

Michael P. Reilly arcege at shore.net
Wed Jun 23 13:06:28 EDT 1999


Dinu C. Gherman <gherman at my-deja.com> wrote:
: This is a nasty question, perhaps, so I appologize in
: advance if its stupidity level is far above the accepted
: average in this newsgroup...

: I would like to do the following:

:>>> class C:
: ...    pass
: ...
:>>>
:>>> c = C()
:>>> C.__class__.__name__ # ok
: 'C'
:>>> c.__name__           # not ok
: Traceback (innermost last):
:   File "<interactive input>", line 0, in ?
: AttributeError: __name__
:>>>

: Question: How to obtain an instance's name at runtime?
: That is I'd like to see this happen (one was or the other):

:>>> c.__name__
: 'c'

: I've checked the reference manual, but it's silent about
: this topic or I'm too blind...

: Fearing-there's-no-such-solution'ly,

: Dinu

There is not reliable solution because instances are not named except as
part of a possible class behavior (__init__ setting self.__name__).
(It is the behavior of classes themselves to have names.)

But you can at least find some of the names bound to this object (within
the current scope, or beyond).

  def whatname(obj):
    import sys
    try:
      raise SystemError
    except:
      tb = sys.exc_info()[-1]
    f = tb.tb_next.tb_frame
    locals = f.f_locals
    globals = f.f_globals
    del tb, f
    for key, item in locals.items() + globals.items():
      if item is obj:
        break
    else:
      raise NameError, 'object not found'  # kind of a reverse namelookup ;)
    return key

This is inaccurate because the object could be passed down from another
module, thru numerous function calls.  And the same could be done for
classes:
  >>> class C:
  ...   pass
  >>> A = C
  >>> c = A()
  >>> c.__class__.__name__
  'C'
  >>>

To make the behavior, then set the "__name__" attribute in the
constructor.
  class C:
    def __init__(self, name='c'):
      self.__name__ = name
  b = C('b')

It may not be what you want, but then Python doesn't quite work like
you might suspect. :)

  -Arcege





More information about the Python-list mailing list