[Tutor] beginning to code

Chris Angelico rosuav at gmail.com
Tue Sep 19 03:46:32 EDT 2017


On Tue, Sep 19, 2017 at 5:22 PM, Antoon Pardon <antoon.pardon at vub.be> wrote:
> But the problem is that the following two pieces of code don't do
> the same in Python.
>
> if x: pass
> if x is True: pass
>
> Sometimes I need that second statement but I can be sure that
> should I show a piece of code on this mailing list with that
> statement, all kind of remarks about it being redundant will
> surface. The fact that x will be interpreted as a boolean
> even if it isn't means that I need that second statement
> when I want to do something only when the value of x is True.

Correct, they're not identical. Under what circumstances do you need
to test for the singleton True value and *not* for truthiness? If this
came up in code review, I would first assume that it's simple
redundancy, because otherwise I have to assume some extremely weird
use of a variable that could be True and could be some other truthy
value. At very least, a check "if x is True:" needs a comment with it.
And in trying to concoct plausible use-cases, I keep falling back on
something like this:

# Display booleans differently
if x is True:
    ... display flag
else:
    ... display number

which would be better represented with "if isinstance(x, bool):"
instead. So "if x is True:" remains odd code, the sort of thing that
MUST be annotated or I would be raising a red flag. Can you give an
actual real-world example where this comes up?

ChrisA



More information about the Python-list mailing list