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

Stephen J. Turnbull stephen at xemacs.org
Thu Mar 6 12:51:29 CET 2014


Shai Berger writes:

 > At issue here is the fact that the idiom doesn't fit where one
 > would expect that it should.

This is the real problem.  People are programming in un-Pythonic style
by analogy to either other languages or to other cases in Python where
the __len__ method provides a natural cast to Boolean, and deciding
since they like the idiom, the behavior of time.time is "unexpected."

But your claim is *not* a "fact".  Quite the reverse, I was mildly
surprised even the last time around that anybody would argue that it's
a good idea to use a sentinel to indicate "uninitialized" and then
fail to test explicitly for the sentinel.

For example, I wouldn't be surprised to see something like this in an
MTA or other program that should not let data out of its sight without
a timestamp:

    my_time = None

    if not my_time and x:
        my_time = x.supposed_to_be_time_but_in_fact_sometimes_0

    if not my_time:
        my_time = time.now()

What are the odds that you'll detect the bug in initializing 'x' in a
timely fashion?  OTOH, if you test for "is None" you'll probably get a
quick TypeError the first time the bug manifests.  (No guarantees, of
course, but why trade a potentially easy bug for a probably hard one?)

If you asked me to implement a Time class, would I have any false
instances?  Quite possibly, yes.  Of course I might implement it as a
namedtuple (h, m, s), in which case it would always be true.  OTOH, I
might implement it as seconds-since-midnight, and probably not bother
to give it a __bool__ method to ensure bool(midnight) == True.

So I don't really care *why* Uncle Timmy chose to make midnight be
false, I only offer kudos for documenting it. :-)


More information about the Python-ideas mailing list