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

Yann Kaiser kaiser.yann at gmail.com
Wed Mar 5 16:08:02 CET 2014


On 5 March 2014 15:34, Skip Montanaro <skip at pobox.com> wrote:
> On Wed, Mar 5, 2014 at 4:44 AM, Paul Moore <p.f.moore at gmail.com> wrote:
>>>     if event.start_time:
>>>         # stuff
>>>
>>> unexpectedly fails if start_time is midnight.
>>
>> Yeah, I was classing that as "application bug" and it's easy to fix
>> with an "is not None".
>
> +1, +1, +1. This is nothing more than an application bug. Issue 13936
> should not be reopened.
>
> This is a very common mistake when None is used as a sentinel value
> (though people normally get away with it), especially by people coming
> from languages having NULL pointers which shall not be named. After
> all, "None" and "NULL" both start with the letter "N". Surely, they
> must represent the same fundamental concept, right? <wink>
>
> Let's change the problem slightly. Instead of time objects, let's
> consider the domain of possible values to be integers. Clearly, None
> is not a member of that set. You could thus use it as a sentinel. So,
> tell me, OP. Would this usage be correct?
>
>     if event.some_id:
>         # stuff
>
> I would argue, "no." I would not argue that 0 should not compare as
> False, however.

You come up with an instance where 0 clearly does not apply as
something to incur a different branch, which is very apparent in just
reading the line, so very easy to spot as a mistake.  But this 0 isn't
a real zero.  It's just a unique identifier that happens to be
implemented as an integer(because it's convenient for your database,
iterators and whatnot.)  Let me show you an actual zero:

    if event.num_attendants:
        prepare_cake()
    else:
        cancel_event()

When no one is coming to your party, is is clearly a different
condition than if any number of people are coming to your event.  When
you read "if num_attendants", you can clearly tell this is going to do
something depending on if people are coming or not.

Let's read this line:

    if not event.date:

How would you read it, knowing nothing about date objects?  I would
read it to mean "has no date been set?" and would naturally continue
the code as such:

    if event.date:
        schedule_event()

I cannot fathom one example where it could read as "does the party
start at midnight?".  Can you?


More information about the Python-ideas mailing list