How to get a unique id for bound methods?

Benji York benji at benjiyork.com
Fri Aug 19 17:24:41 EDT 2005


Russell E. Owen wrote:
> The id of two different methods of the same object seems to be the 
> same, and it may not be stable either.

Two facts you're (apparently) unaware of are conspiring against you:

1) the "id" of an object is consistent for the lifetime of the object, 
but may be reused after the object goes away

2) methods are bound on an as-needed basis and then normally discarded 
(unless you do something to keep them around)

An illustration:

class cls(object):
   def meth1(self):
     pass
   def meth2(self):
     pass

c = cls()
m1 = c.meth1
print id(m1)
-1209779308
m2 = c.meth1
print id(m2)
-1209652732

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

Nope, they're objects, they just don't tend to be around very long.

> 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.

I think you'll get the best advice from this group if you tell us what 
the larger problem is that you're trying to solve.
--
Benji York




More information about the Python-list mailing list