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

Ben Finney ben+python at benfinney.id.au
Thu Aug 9 05:23:40 CEST 2012


Rob Cliffe <rob.cliffe at btinternet.com> writes:

> On 08/08/2012 17:59, Oleg Broytman wrote:
> > On Thu, Aug 09, 2012 at 02:18:53AM +1000, Ben Finney <ben+python at benfinney.id.au> wrote:
> >> What is a compelling use case for checking precisely for True or
> >> False?

By “compelling use case for”, I mean “a use case which is best satisfied
by”. So use cases which *could* use this are not compelling if they are
better satisfied by some other, existing way.

>     1) I have written a function that returns True, False or a string
> error message. (No doubt an Exception-subclass object might be better
> style.)

You get to the nub of it: there are clearly better ways to meet the use
case (for this one, use an exception), so this is not a compelling use
case for precise checking of True and False.

>     2) Say you are writing a function to process an arbitrary object, e.g.
> a custom version of repr.  You might well choose to write
>         if obj is True:
>             # processing
>        elif obj is False:
>            # processing
>        elif type(obj) is int:
>             # processing

Again, this is much clearer written as:

    if type(obj) is bool:
        # processing
    if type(obj) is int:
        # processing

So not a compelling use case for checking specific values.

> I am sure the examples could be multiplied.
> I can see no reason why we should be discouraged from writing
>     if x is True:
> if that is really what we mean (and need) and not just a verbose way of
> spelling "if x:".

I don't see any of the cases presented so far (other than unit testing,
which is already special enough to break most of the rules) as best
satisfied by precise checking for specific values of bool.

On the other hand, ‘if foo is True’ is a common beginner mistake that we
meet frequently in ‘comp.lang.python’, and is almost always better
written as ‘if foo’. It's that kind of advice that belongs in PEP 8.

-- 
 \        “The difference between religions and cults is determined by |
  `\                      how much real estate is owned.” —Frank Zappa |
_o__)                                                                  |
Ben Finney




More information about the Python-ideas mailing list