0

I want to check if a variable is True (not just its truthiness).

This is easily checked like this:

>>> a = 1
>>> isinstance(a, bool) and a
False

>>> a = True
>>> isinstance(a, bool) and a
True

Of course, that is totally fine. However, the same behaviour can be seen in the following code:

>>> a = 1
>>> a is True
False

>>> a = True
>>> a is True
True

In my opinion, the second snippet is a bit more readable (if you understand how is works). With Python 3.8, I get a SyntaxWarning when executing the second snippet. Would the second example work with all Python implementations? Is there a guarantee that bool objects of the same value are identical in this way? I believe I have read somewhere that this is not guaranteed for int objects. Is it ever ok to check literal values with is like this?

Onno Eberhard
  • 1,341
  • 1
  • 10
  • 18
  • 7
    Short answer: When you want an equality check, _do an equality check_, not an identity check. Behaviors which are present as optimizations are not guaranteed; and it's only safe to rely on a language feature (in a future-proofing / alternate-implementation-compatibility sense of "safe") where that feature is actually part of the documented spec. – Charles Duffy Aug 21 '20 at 18:36
  • 1
    What exactly does the `SyntaxWarning ` say? – superb rain Aug 21 '20 at 18:38
  • 1
    "With Python 3.8, I get a SyntaxWarning when executing the second snippet." I do not. Please post the exact error message. – MisterMiyagi Aug 21 '20 at 18:39
  • Partial duplicate: [Is there only one True and one False object in Python?](https://stackoverflow.com/q/24842852/4518341) – wjandrea Aug 21 '20 at 18:44
  • Thanks for the feedback! @wjandrea the answers from your link did answer my question. According to PEP 285, `True` and `False` are indeed singletons and so `x is True` is guaranteed to be equivalent to `isinstance(x, bool) and x`. – Onno Eberhard Aug 21 '20 at 19:15
  • 1
    The `SyntaxWarning` says `SyntaxWarning: "is" with a literal. Did you mean "=="?` – Onno Eberhard Aug 21 '20 at 19:16

0 Answers0