Reputation: 2043
This code snippet is really puzzling me:
class O(object):
pass
O() == O() # False
O() is O() # False
hash(O()) == hash(O()) # True !
id(O()) == id(O()) # True !!!
I always thought that the is
operator was comparing id
s, and that the default instance equality check (==
) also compared id
s, or at least hash
es:
How can 2 class instances share the same id
, but not be equal in any way ??
I'm using CPython 2.7.6.
Upvotes: 3
Views: 79
Reputation: 37003
They don't "share the same id". In CPython (the most-used implementation) the id
function returns the memory address of the Python object it is given as an argument. What's happening is that the objects are being garbage-collected, and the memory is being re-used. id
s are only guaranteed unique for objects existing simultaneously. If you bind the objects to names you get a more sensible result:
>>> class O(object):
... pass
...
>>> o1 = O() ; o2 = O()
>>> o1 == o2
False
>>> o1 is o2
False
>>> hash(o1) == hash(o2)
False
>>> id(o1) == id(o2)
False
Upvotes: 4
Reputation: 15040
The answer is in this question.
In CPython, id
returns the pointer where the data is stored.
In your example the GC is removing the old object before the comparinson. The second object is placed where the first was, thus returning the same value for id
.
Upvotes: 4