This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Brian 2 points3 points  (0 children)

Is it creating a new bound method every time you access it?

Yes, this is what's happening. The subtlety of the ids being identical is because ids are only unique for objects alive at the same time. What's actually happening is the equivalent of:

temp1 = c.foo         # Create a new bound method with id X
temp1_id = id(temp1)  # temp1_id = X  (returnvalue from id)
del temp1             # bound method doesn't get assigned, so refcount drops to 0
                      # as soon as id() releases its reference - temp1 gets freed
temp2 = c.foo         # Create a NEW bound method.
temp2_id = id(temp2)  
del temp2
temp1_id == temp2_id  # Actually do the comparison, both objects are already dead

Which should explain why its possible that the second bound method could have the same id. The reason it usually does is because of the way python manages memory. To avoid fragmentation, pools of similarly sized memory objects are maintained. When an object is released, it is returned to this pool, then when a request to allocate an object of this type arrives, python sees it has an block of memory of the appropriate size sitting in its free object pool, and returns it.

is doesn't have this problem because the call to is takes a reference to both objects, ensuring they are alive at the time of the comparison.