Search code examples
pythonobjecthashequality

How can 2 objects be considered not equal and not identicial by Python, but have the same id?


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 ids, and that the default instance equality check (==) also compared ids, or at least hashes:

How can 2 class instances share the same id, but not be equal in any way ??

I'm using CPython 2.7.6.


Solution

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