Boolean comparison & PEP8

Marko Rauhamaa marko at pacujo.net
Sun Jul 28 15:22:30 EDT 2019


Jonathan Moules <jonathan-lists at lightpear.com>:

> Lets say I want to know if the value of `x` is bool(True).
> My preferred way to do it is:
>
> if x is True:
> [...]
>
> But this appears to be explicitly called out as being "Worse" in PEP8:
>
> [...]
>
> Why?

It has primarily to do with the naturalness of expression. In English,
you say:

   If you have a moment, I'll show you.

   If you had a dog, you'd understand.

instead of:

   If your having a moment is true, I'll show you.

   If your having a dog were true, you'd understand.

By the same vein, in Python you say:

   if len(students) < 7:
       klass.cancel()

rather than:

   if (len(students) < 7) is True:
       klass.cancel()


Furthermore, while True and False are singleton objects, referring to
them through the "is" operator seems strikingly ontological in most
contexts. You are no longer interested in the message of the letter but
the fibers of the paper it was written on.

I *could* imagine a special case where a positional argument's semantics
would depend on the specific object. For example,

   >>> os.path.exists(False)
   True

is rather funky and the os.path.exists function would probably benefit
from a check such as:

   if path is True or path is False:
       raise Hell()

but even in such cases, it is more customary to say:

   if isinstance(path, bool):
       raise Hell()


Marko



More information about the Python-list mailing list