[Python-ideas] Please reconsider the Boolean evaluation of midnight

Stephen J. Turnbull stephen at xemacs.org
Thu Mar 6 11:57:27 CET 2014


Shai Berger writes:

 > Unless you're aware of the issue, you are not going to unit-test
 > specifically for midnight. If you are aware, you don't need to
 > detect it, you write "is not None".

The issue, as Skip has argued at length, is that by using the implicit
cast to Boolean you've changed the nature of the test from "membership
in valid values" to "a true-ish value".[1]

This can be detected generically with grep, something like:

    grep -E '^ *if [^<>=]*:' | grep -v '^ *if.* is .*:'

with a (possibly large) number of false positives.  (I suspect it's
not worth worrying about no false negatives; if the 'is' operator is
present, the test is boolean except if it's part of an arithmetic
expression such as "3 + (2 is not None)".)  You might want to include
modulo (%) in the list of operators.  Or it might be more accurate to
check for bare variables only and assume any expression should OK.

The false positives can be drastically reduced by checking for a
Boolean or container initializer in the case of "if var:".  None of
pep8, pylint, or pychecker does this now AFAICT, but they could, I
think.

Footnotes: 
[1]  Implementing a membership test as a test for a sentinel is a
bit fishy in this context of arguing about the "nature of the test",
but given the much less obvious nature of the conversion to bool in
complex types like dates and times, I'll go with Skip any time.



More information about the Python-ideas mailing list