22
The is operator is used test for identity.
I was wondering if the is operator and id() function call any __magic__ method, the way == calls __eq__.
I had some fun checking out __hash__:
class Foo(object):
def __hash__(self):
return random.randint(0, 2 ** 32)
a = Foo()
b = {}
for i in range(5000):
b[a] = i
Think about dict b and the value of b[a]
Every subsequent lookup of
d[a]is either aKeyErroror a random integer.
But as the docs on the special methods state
[the default implementation of] x.
__hash__() returns id(x).
So there is relation between the two, but just the other way around.
I've seen many questions on is and id here, and the answers have helped many confused minds, but I couldn't find an answer to this one.