4

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?

Luca Fülbier
  • 2,641
  • 1
  • 26
  • 43

2 Answers2

4

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.

taleinat
  • 8,441
  • 1
  • 30
  • 44
  • 1
    Note that `__bool__` is Python 3.X and the Python 2.X equivalent is `__nonzero__`. Also, if you're going through the trouble of defining `__bool__`, then `if MyBool()` would still be the most pythonic truthiness test. – Jared Goguen Jan 22 '16 at 15:58
3

is is "worse" in this context, because requires exact object. First suggestion allows maximal duck-typing, second allows some typical truthy values, last one disallows you for any duck-typing. Only True singleton will pass a comparison.

This comparison is successful:

1 == True 

This comparison is unsuccessful:

1 is True
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
  • But people would seriously doubt your skills if you wrote `if cond == True:` instead if `if cond:`, or `if cond == False:` instead of `if not cond:`. – Kijewski Jan 22 '16 at 15:52
  • This was the most relevant thing noted in the possible duplicate question in the comment above. It seems like the principle of maximal duck typing is guiding the PEP8 specification. – Jared Goguen Jan 22 '16 at 15:54
  • @Kay Bad habits have deep roots. I find myself doing the same in other languages as well. I will try to remember avoiding that and maybe rethink my variable/function names if i feel the need to explicitly compare against true/false in the future. – Luca Fülbier Jan 22 '16 at 16:05