Lucas Cimon
Lucas Cimon

Reputation: 2043

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.

Upvotes: 3

Views: 79

Answers (2)

holdenweb
holdenweb

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

noxdafox
noxdafox

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

Related Questions