The basics
I believe your confusion might come from comparing Python to languages such as JavaScript where there is a ==
and a ===
operator. Python does not work this way.
In Python the only way to compare for equality is with ==
and this compares both value and type.
Thus if you compare True == "dog"
, then the expression is immediately False
because the types bool
and str
are not types that can be compared.
Although, note that it does not mean that there are no types that are comparable between themselves. Examples are set
and frozenset
:
frozenset({1,2,3}) == {1,2,3} # True
Or simply int
and float
1 == 1.0 # True
This is the behaviour for most built-in types.
The classy part
In the case where you define your own types, i.e. when you define classes, you can write the __eq__
which is called when you compare a class object to another value.
By example you could do this (which by the way was pointed out as a terrible idea in the comments, you should not inherit built-in types).
class WeirdString(str):
def __eq__(self, other):
return str(self) == str(other) or bool(self) == bool(other)
s = WeirdString("dog")
s == True # True
In the case where you do not define __eq__
, then Python fall back on comparing whether the objects are the same object with is
.