So many tutorials have stated that the ==
comparison operator is for value equality, like in this answer, quote:
==
is for value equality. Use it when you would like to know if two objects have the same value.is
is for reference equality. Use it when you would like to know if two references refer to the same object.
However, I found that the Python doc says that:
x==y
callsx.__eq__(y)
. By default,object
implements__eq__()
by usingis
, returningNotImplemented
in the case of a false comparison:True if x is y else NotImplemented
."
It seems the default behavior of the ==
operator is to compare the reference quality like the is
operator, which contradicts what these tutorials say.
So what exactly should I use ==
for? value equality or reference equality? Or it just depends on how you implement the __eq__
method.
I think the doc of Value comparisons has illustrated this question clearly:
The operators
<
,>
,==
,>=
,<=
, and!=
compare the values of two objects. The value of an object is a rather abstract notion in Python. Comparison operators implement a particular notion of what the value of an object is. One can think of them as defining the value of an object indirectly, by means of their comparison implementation.
The behavior of the default equality comparison, that instances with different identities are always unequal, may be in contrast to what types will need that have a sensible definition of object value and value-based equality. Such types will need to customize their comparison behavior, and in fact, a number of built-in types have done that.
The default behavior for equality comparison (
==
and!=
) is based on the identity of the objects. Hence, equality comparison of instances with the same identity results in equality, and equality comparison of instances with different identities results in inequality. A motivation for this default behavior is the desire that all objects should be reflexive (i.e.x is y
impliesx == y
).
It also includes a list that describes the comparison behavior of the most important built-in types like numbers, strings and sequences, etc.