PEP8 states that checks for None
should be performed using is None
. The same holds true for singletons in general. But PEP8 also states, that equality to True and False should not be performed using an operator, is
being even worse than ==
:
Yes: if greeting:
No: if greeting == True:
Worse: if greeting is True:
I understand that the first one is the prettiest and most pythonic way, but sometimes i find myself in a situation where i want to explicitly show that i am comparing against True
or False
. How is is
worse than ==
in that situation?
The equality operator ==
can be implemented by classes (as well as all other comparison operators), but is
cannot.
A class could be defined so that some of its instances are equal to True
, but they will still always fail the is True
comparison. Consider a bool-like class, for example:
class MyBool:
def __init__(self, is_true):
self.is_true = bool(is_true)
def __eq__(self, other):
return self.is_true == bool(other)
def __bool__(self):
return self.is_true
This class can make sure that for an instance a = MyBool(True)
, all of if a:
, bool(a)
and a == True
will behave properly. However, a is True
will return False
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With