[Python-ideas] Programming recommendations (PEP 8) and boolean values

Steven D'Aprano steve at pearwood.info
Thu Aug 9 18:14:43 CEST 2012


On 09/08/12 17:15, Antoine Pitrou wrote:
> Le 08/08/2012 16:28, Guido van Rossum a écrit :
>> I'd be strongly against changing that rule. If you don't want other
>> types than bool, use an isinstance check. Code using "is True" is most
>> likely a bug. (It's different for None, since that has no second value
>> that is assumed.)
>
> That said, I'm also curious about the answer to Michael's following question:
> “why does it say that using an identity check is worse than an equality check?”


1) Identity checks put the emphasis on the wrong thing: object identity rather
than value. Why do you care that True and False are singletons? Your algorithm
almost certainly does not depend on that fact. And who knows? Perhaps some day
your code will be running on some Python implementation which fails to enforce
True and False being singletons.

2) In old code, 0 and 1 were the idiomatic flags. 0 == False and 1 == True,
but if you use identity checks, your code will unnecessarily break old code.


Postel's Law (the Robustness Principle) tells us that we should be strict in
what we send and liberal in what we accept. This rule has greater applicability
than just networking. It tells us that when returning a boolean flag, we should
strictly always return True or False. But when accepting a boolean flag as
argument to our function, we should not unnecessarily limit what counts as a
valid argument.

So in order of preference:

1) under most circumstances, we should accept duck-typed truthy values
    (e.g. use "if x") as the most liberal way to test a flag in Python;

2) if we have a good reason not to duck-type a flag, then next best
    is to compare by value, not identity ("if x == True");

3) least preferred (worst) is to be a Boolean Fascist and only accept
    True and False by identity ("if x is True").


There may be some cases where you rightly wish to insist on an actual
bool rather than any truthy or falsey value, but that should be the
exception rather than the rule.



-- 
Steven



More information about the Python-ideas mailing list