Note 18.3.1. Beware of ==.
“When I use a word,” Humpty Dumpty said, in a rather scornful tone, “it means just what I choose it to mean — neither more nor less.” Alice in Wonderland
Python has a powerful feature that allows a designer of a class to decide what an operation like
==
or <
should mean. (We’ve just shown how we can control how our own objects are converted to strings, so we’ve already made a start!) We’ll cover more detail later. But sometimes the implementors will attach shallow equality semantics, and sometimes deep equality, as shown in this little experiment:p = Point(4, 2)
s = Point(4, 2)
print("== on Points returns", p == s) # by default, == does a shallow equality test here
a = [2, 3]
b = [2, 3]
print("== on lists returns", a == b) # by default, == does a deep equality test on lists
This outputs:
== on Points returns False == on lists returns True
So we conclude that even though the two lists (or tuples, etc.) are distinct objects with different memory addresses, in one case the
==
operator tests for deep equality, while in the case of points it makes a shallow test.