True inconsistency in Python

Michael Geary Mike at DeleteThis.Geary.com
Mon Nov 17 13:14:39 EST 2003


KefX:
> Well, actually, some coding standards suggest you always compare against
false.
> This is so the code is slightly more clear, and "!= false" avoids the
pitfall
> that "== true" has. The problem of course is that some unwitting
maintenance
> programmer may decide that "== true" os more clear than "!= false", not
> realizing it is wrong...which is why all maintenance programmers should
read
> programming standards. :) We can't program in baby C just for them, after
all,
> but we shouldn't make things unnecessarily difficult for them either, but
I
> think we have bigger things to worry about if a maintenance programmer
fails to
> understand such a simple concept after being told about it.
>
> Now of course any idiot C (or C++, or Java) programmer knows that these
two are
> equivalent:
>
> if(blah != false)
>   do_blah();
>
> if(blah)
>   do_blah();
>
> But if whatever goes in "blah" is really long (and often it is), you very
> quickly see what is being compared: it's a straight boolean comparison,
whereas
> with the second you have to look at the whole thing, find no comparison
> operator, and go, "oh, there's no explicit comparison so it's obviously an
> implicit straight boolean comparison". This is especially valuable in
really
> long 'if' statements, such as one might want for an inverse parser (don't
worry
> if you don't know what one is). The idea is if you compare against 'false'
all
> the time, you won't forget it when it would actually give the code more
> clarity.

That strikes me as a really bad practice, in C, Python, or any language with
a similar if statement. Code should read the way people think, and people
don't tack on "!= false" when they make decisions based on conditions.

Which would you say: "If you're hungry, eat!" or "If your hunger is not
equal to false, eat!"

So which is more clear:

if( hungry )
    eat();

or:

if( hungry != false )
    eat();

It's just as bad when you want to make the opposite test. Do you say, "If
you're not hungry, don't eat!" or "If your hunger is equal to false, don't
eat!"

So do you code:

if( ! hungry )
    dontEat();

or:

if( hungry == false )
    dontEat();

(For those not familiar with C, "!" is the logical not operator and is
pronounced "not".)

I don't buy the argument that "you have to look at the whole thing, find no
comparison operator, and go, 'oh, there's no explicit comparison so it's
obviously an implicit straight boolean comparison.'" You *always* have to
look at the whole thing, and an if statement always tests its entire
argument for truth or falsity. Adding an explicit "!= false" or "== false"
simply adds noise and reduces clarity.

Comparing against a boolean isn't discouraged in Python because of some
arbitrary cultural preference, it's discouraged because it makes code harder
to read and understand.

-Mike






More information about the Python-list mailing list