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

Lefavor, Matthew (GSFC-582.0)[MICROTEL LLC] matthew.lefavor at nasa.gov
Thu Aug 9 00:39:42 CEST 2012

I don't think PEP 8 is meant to cover a specialized cases like testing.
Keep in mind the recommendation in the beginning of the style guide: "But
most importantly: know when to be inconsistent -- sometimes the style
guide just doesn't apply."

For example, a similar argument to yours could be made about the
recommendation to "use the fact that empty sequences are false" instead of
checking len(sequence). E.g.:

Yes: if not seq:
     if seq
No: if len(seq)
    If not len(seq)

If you want to test that your __len__ method is working, then of course
the latter would be acceptable--because you aren't concerned about
checking that the list is full; you're concerned about the functionality
of the __len__ method. Common sense should indicate that the style guide
doesn't apply here because the use case is different.

The same goes for truth or falsity. In situations in which you are
concerned about the truth or falsity of an object, then you should never
use "== True" or "is True", because of the possibility of bugs that others
have already pointed out.

There are clearly cases in which the style guide just doesn't
apply--testing to ensure that a returned value actually "is" a given
singleton is one of them. The style guide need not list every case in
which the recommendation possibly might not apply. People with advanced
needs are advanced enough to know when to break the style guide. =)

Matthew Lefavor

From:  Michael Foord <fuzzyman at gmail.com>
Date:  Wednesday, August 8, 2012 6:04 PM
To:  "python-ideas at python.org" <python-ideas at python.org>
Subject:  Re: [Python-ideas] Programming recommendations (PEP 8) and
boolean	values

On 8 August 2012 17:59, Oleg Broytman <phd at phdru.name> wrote:

On Thu, Aug 09, 2012 at 02:18:53AM +1000, Ben Finney
<ben+python at benfinney.id.au <mailto:ben%2Bpython at benfinney.id.au>> wrote:
> What is a compelling use case for checking precisely for True or False?

   To distinguish False and None for a tri-state variable that can have
3 values - "yes", "no" and "unspecified" - True, False and None in

Or when testing, I often want to check that a method *really* returns True
or False rather than some object that happens to evaluate to True or False.


     Oleg Broytman            http://phdru.name/            phd at phdru.name
           Programmers don't die, they just GOSUB without RETURN.
Python-ideas mailing list
Python-ideas at python.org


May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html

More information about the Python-ideas mailing list