Search⌘ K

Deep Down, We're All the Same

Learn how Python's object identity and hash functions work under the hood, including why two objects can share the same id and hash but not compare equal. Understand how object lifetime and destruction affect the behavior of the is operator and avoid common misconceptions about Python classes.

We'll cover the following...

Do Python classes behave “oddly”? Let’s find out!

C++
class FTW:
pass
print(FTW() == FTW()) # two different instances can't be equal
print(FTW() is FTW()) # identities are also different
print(hash(FTW()) == hash(FTW())) # hashes should be different as well

So, with two objects that don’t compare equal but have the same hash, will there be a hash collision? Not really; there’s another twist to this story.

C++
print(id(FTW()) == id(FTW()))

How can two objects not ...