Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is comparison to True/False using the "is" operator bad? [duplicate]

Tags:

python

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?

like image 656
Luca Fülbier Avatar asked Mar 13 '23 12:03

Luca Fülbier


1 Answers

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.

like image 156
taleinat Avatar answered Mar 23 '23 00:03

taleinat