How to obtain the reference name

Bjorn Pettersen BPettersen at NAREX.com
Tue Mar 11 21:00:16 EST 2003


> From: Paco [mailto:barreraf at inicia.es] 
> 
> Hy, somebody know how to obtain the name of an instance out 
> of any methods of the claas.
> Example:
> 
> class A:
>     def __init__(self):
>         print 'hello'
> 
> j=A()
> 
> I need to obtain the name of the instance "j", something as 
> is: "j.name" and the value returned was "j"

First of all, trust me when I say the only reason you would need this is
because of a design mistake, please take a second look and save yourself
a lot of trouble. 

Just, for fun however:

   def getSimpleNamesInCurrentModule(obj):
     frames = []
     try:
       for i in range(2, 42):
         frames.append(sys._getframe(i))
     except ValueError:
       pass
       
     names = []
     for frame in frames:
       for var, val in frame.f_locals.items():
         if id(val) == id(obj):
           names.append(var)
     return names
     
   class C(object):
     def myNames(self):
       return getSimpleNamesInCurrentModule(self)
   
   c = C()
   d = c
   
   class E(object):
     def __init__(self, obj):
       self.obj = obj
       
   e = E(d)
       
   def a(obj1):
     def b(obj2):
       def c(obj3):
         cvar = obj3
         print cvar.myNames()
       
       bvar = obj2
       c(bvar)
     avar = obj1
     b(avar)
   
   a(d)

will print:

  ['cvar', 'obj3', 'obj2', 'bvar', 'obj1', 'avar', 'd', 'c']

note, no mention of e.obj. Also, if you write a module, m, and in it:

  import yourModule
  print yourModule.d.myNames()     # []
  f = yourModule.d
  print f.myNames()                # ['f']
  g = yourModule.C()
  print g.myNames()                # ['g']

If you care enough to worry about this I shudder <wink> and leave it as
an excercise.

-- bjorn





More information about the Python-list mailing list