Is there a strict comparison operator like ===in Python?
Just the usual comparison via == does not work as it should:
>>> 0 == False
True
4
3 answers
If the essence of the question is to compare values and types, then you can do this:
def strict_eq(obj1, obj2):
if type(obj1) != type(obj2):
return False
return obj1 == obj2
In [4]: strict_eq(0, False)
Out[4]: False
PS you can go even further and for numeric types compare numbers up to a certain precision to avoid known floating point problems:
In [5]: 0.1 + 0.2 == 0.3
Out[5]: False
Strict comparison function with a certain accuracy:
from numbers import Number
def strict_eq(obj1, obj2, epsilon=1e-7):
if type(obj1) != type(obj2):
return False
if isinstance(obj1, Number):
return abs(obj1 - obj2) < epsilon
return obj1 == obj2
In [10]: strict_eq(0.1 + 0.2, 0.3)
Out[10]: True
9
Author: MaxU, 2020-05-01 13:47:31
For many cases, it is possible to apply the comparison of id
s:
id(0) == id(False)
False
This doesn't exactly match the ===
operator (JavaScript), but it can be useful.
1
Author: MarianD, 2020-05-01 07:00:54
What exactly is confusing you? In Python
True = 1
, a False = 0
. If you need to compare exactly the words True
and False
, then just take them as strings for example 0 == "False"
0
Author: DGDays, 2020-05-01 05:28:02