Boolean comparison & PEP8

Chris Angelico rosuav at gmail.com
Sun Jul 28 20:04:36 EDT 2019


On Mon, Jul 29, 2019 at 9:48 AM Michael Torrie <torriem at gmail.com> wrote:
>
> On 7/28/19 5:55 AM, Jonathan Moules wrote:
> > But this appears to be explicitly called out as being "Worse" in PEP8:
> >
> > """
> > Don't compare boolean values to True or False using ==.
> >
> > Yes:   if greeting:
> > No:    if greeting == True:
> > Worse: if greeting is True:
> > """
>
> Yet the recommended solution to the problem of wanting a default
> argument of an empty list is something like this:
>
> def foo(bar=False);
>     if bar is False:
>         bar = []
>
>     ....
>
> Clearly in this case the expression "not bar" would be incorrect.

This is a fairly unusual case, though. More commonly, the default
would be None, not False, and "if bar is None:" is extremely well
known and idiomatic.

> There's a difference between looking for a particular identity or
> sentinel, and checking for truthiness or falsiness.
>
> So I guess it all depends on what you need to do. If you just need to
> check truthiness, just do "if greeting"  If you need to know if the
> variable is some particular sentinel, use the "if greeting is whatever".

This analysis is correct, but the situations where you *actually* want
to know if something "is True" or "is False" are rare enough that PEP
8 doesn't need to mention them; whereas the case where you actually
just need the truthiness is so common (and so often miswritten) that
it's worth being clear on it.

ChrisA



More information about the Python-list mailing list