[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Boolean comparison & PEP8

I think the other part of the discussion to be had here is: how do you name your booleans?

As with other things, "x", and "greeting" aren't really the best names. "greeting" sounds like it should hold what the greeting _is_, not whether or not there _should be_ a greeting. If it were something like "greetingRequired" or "greetingRequested" then it gets to be more readable as to what you're storing and looking for with the variable.

if greeting:


if greetingRequired:

I think the "greetingRequired" version is much more readable. To me the name of a boolean variable should be obvious that it's a boolean, be it as a statement or as an instruction. Looking at the arguments for subprocess.popen for example, lets put some of the boolean arguments behind an if and see how readable they are:

if start_new_session:
    #instruction, I need to "start (a) new session"

if close_fds:
    #instruction, I need to "close file descriptors"

if restore_signals:
    #instruction, I need to "restore signals"

if shell:
    #wait, "shell" is not really a statement or an instruction. "If shell"... what? "I need to shell"? Is this whether we want to use a shell, or if we discovered that we're already in one? Or is "shell" not really a boolean, and is holding which shell we want, and we're just using the "truthyness" to make sure it's not None? What's going on here? Dangit, ok, where's the documentation?
(subprocess is common enough that people know this, but imagine a much less frequently used module/function)

Do I have a point or am I just smoking crack? Does anyone else have examples?

-----Original Message-----
From: Python-list <python-list-bounces+david.raymond=tomtom.com at python.org> On Behalf Of Jonathan Moules
Sent: Sunday, July 28, 2019 7:56 AM
To: python-list at python.org
Subject: Boolean comparison & PEP8

Hi List,
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:
 ??? pass

Because this tests both the value and the type.

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:


If `x` can also have a value of "1"(str) or 1(int) then in both cases 
this would be a false positive if I were to do the below as they'll both 
equate to True:

if x:
 ??? pass

The PEP for boolean type (285 - 
https://www.python.org/dev/peps/pep-0285/) doesn't mention the "is" 
comparison keyword at all as far as I can tell.

What am I missing?