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

Stephen J. Turnbull stephen at xemacs.org
Thu Mar 6 18:40:42 CET 2014


Antoine Pitrou writes:
 > Le 06/03/2014 15:33, Stephen J. Turnbull a écrit :

 > > never get fixed, and that "if var:" which is actually testing for
 > > identity with a false-y sentinel is still strongly discouraged.
 > 
 > Why "strongly discouraged"? This is more of a style issue than anything 
 > else?

No, it's not just a style issue.  As Skip points out, it's a
*semantic* issue as well.  You're really testing for not for the
boolean value of values of one type, but for a difference of type
("initialized whatever" vs "uninitialized variable").  Pragmatically,
this would be half a dozen of one, six of the other, except that there
are two more possibilities: a false-y of a different type, and a
truth-y of a different type.  I don't think the spurious truth-y
matters very much ... you'd expect a TypeError to be raised pretty
quickly, and if not, it's a bad bug (by the time you notice the bad
value, it's really hard to work back to where and why it's been
injected).

The spurious false-y, on the other hand, seems quite likely to lead to
spurious values *of the expected type*.  To restate my earlier example:

    my_time = None

    if not my_time and x:
        my_time = x.expected_to_be_parsed_time_but_parse_bug_returns_0

    if not my_time:
        my_time = time.now()

You may never catch *that* parser bug, because the value of 'my_time'
always looks right (ie, like a datetime.time value).  But in

    my_time = None

    if my_time is None and x:
        my_time = x.expected_to_be_parsed_time_but_parse_bug_returns_0

    if my_time is None:
        my_time = time.now()

you're on the same footing as with the truth-y -- just a bit lucky and
you get a quick TypeError.  This is an objective benefit (although you
can say "the probability that there will be a bug to catch is too low
to care about" if you like, it's obviously bigger than zero).

I also value the psychological benefit of being precise here.  I'm not
even sure it's possible to fool 'is' into thinking some other object
is None, but people do a great job of convincing themselves of things
like "datetime.time objects can't be false" all the time.  Use the
"is None" idiom and you know exactly what you're doing.  This latter
is close to "just style", of course.

Steve




More information about the Python-ideas mailing list