bizarre id() results

Delaney, Timothy (Tim) tdelaney at avaya.com
Thu Dec 15 16:34:32 EST 2005


Stuart McGraw wrote:

> Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]
> on win32 Type "help", "copyright", "credits" or "license" for more
> information. 
>>>> class A:
> ...  def m1(self): print "m1"
> ...  def m2(self): print "m2"
> ...
>>>> a = A()
>>>> a.m1()
> m1
>>>> a.m2()
> m2
> # ok, both methods work and give the expected results
> # so i presume they are different methods.
>>>> id(a.m1)
> 9202984
>>>> id(a.m2)
> 9202984
>>>> id(a.m1)==id(a.m2)
> True
> # Huh? They seem to be the same.

Bound methods are created on the fly. The id() of an object is its
memory address (effectively). The sequence of events you have are:

obtain reference to bound method a.m1
    creates a new bound method
call id()
release reference to bound method a.m1
    releases memory back to be reused

obtain reference to bound method a.m1
    creates a new bound method
call id()
release reference to bound method a.m2
    releases memory back to be reused

Because of the way Python's memory allocator works, the second bound
method created reused the same memory as the just-released bound method,
and hence gave the same id().

Now, if you hold onto the bound methods, you will see that they get
different IDs.

>>> class A:
...     def m1 (self): print "m1"
...     def m2 (self): print "m2"
...
>>> a = A()
>>> m1 = a.m1
>>> m2 = a.m2
>>> id(m1)
10378576
>>> id(m2)
10383408

Tim Delaney



More information about the Python-list mailing list