0

I know that this question has been asked a bunch of times (for this I apologize), and PEP8 "covers" it by saying that if x is True << x == True << if x, but I still don't understand why. It is my understanding that both None and True are singletons in Python, so I don't quite see the nuance. This especially confuses me because PEP8 says:

Comparisons to singletons like None should always be done with is or is not, never the equality operators.

I also understand that the if x syntax covers a few more cases than if x is True in that if x can do things like check for a non-empty string/list/etc or a non-zero number, but in the case where you know x is a boolean value, why is it so incorrect to compare with is?

Is the reason that PEP8 assumes that if x is safer because it covers the case that if x is True covers and those other cases I referenced above?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Kmanc
  • 349
  • 1
  • 5
  • 20
  • `True` and `False` are _literals_ – paddy Jan 18 '21 at 20:21
  • 2
    `None` is guaranteed to be a singleton by the language definition. `True` is a singleton only by the optimization of the CPython interpreter. – Klaus D. Jan 18 '21 at 20:23
  • It's not necessarily *incorrect* to use `x is True`. In some specific cases it's *correct*, see https://stackoverflow.com/questions/27276610/boolean-identity-true-vs-is-true – mkrieger1 Jan 18 '21 at 20:26
  • 2
    @KlausD. [citation needed] :-) – Kelly Bundy Jan 18 '21 at 20:28
  • More specifically, your question is closer to this one: https://stackoverflow.com/questions/4050335/strange-pep8-recommendation-on-comparing-boolean-values-to-true-or-false – mkrieger1 Jan 18 '21 at 20:30
  • I won't be surprised if the root of this goes back to Python 2 (and perhaps 1...), where one could easily override the values of `True` and `False`: `orig_true = True ; orig_false = False ; True = 1 ; False = 0 ; print orig_true == True ; print orig_true is True` This beauty outputs `True, False` – DeepSpace Jan 18 '21 at 20:31
  • This answer quotes a key information from the docs: https://stackoverflow.com/a/24846681/5378816 . If `True` and `False` are the only two boolean objects, they must be singletons. Otherwise a third boolean object could be created. – VPfB Jan 18 '21 at 20:44
  • @KellyBundy Wrong website! – Klaus D. Jan 18 '21 at 21:26
  • @KlausD. More like wrong claim (your original comment). – Kelly Bundy Jan 18 '21 at 22:24
  • Ahhhh @KlausD. that was the missing piece of info for me. Thank you for that, that's super helpful! – Kmanc Jan 19 '21 at 21:25

0 Answers0