How to get a unique id for bound methods?

Russell E. Owen rowen at cesmail.net
Fri Aug 19 16:29:19 EDT 2005


I have several situations in my code where I want a unique identifier 
for a method of some object (I think this is called a bound method). I 
want this id to be both unique to that method and also stable (so I can 
regenerate it later if necessary).

I thought the id function was the obvious choice, but it doesn't seem to 
work. The id of two different methods of the same object seems to be the 
same, and it may not be stable either. For instance:

class cls(object):
  def __init__(self):
    print id(self.meth1)
    print id(self.meth2)
  def meth1(self):
    pass
  def meth2(self):
    pass

c = cls()
3741536
3741536
print id(c.meth1)
3616240
print id(c.meth2)
3616240

I guess that just means bound methods aren't objects in their own right, 
but it surprised me.

The "hash" function looks promising -- it prints out consistent values 
if I use it instead of "id" in the code above. Is it stable and unique? 
The documentation talks about "objects" again, which given the behavior 
of id makes me pretty nervous.

Any advice would be much appreciated.

-- Russell



More information about the Python-list mailing list