Live data from Hacker News

Please reconsider the Boolean evaluation of midnight

mail.python.org

1–10 of 218 posts

Re: Please reconsider the Boolean evaluation of midnight

#2
I just got bit by this a few days ago. I was creating an event scheduling system that uses either repeating entries with a datetime.time, or one time entries with a datetime.datetime. I had code that said "if start_time" to see which it was, and discovered later that midnight evaluates to false. It's not the best idea.

Re: Please reconsider the Boolean evaluation of midnight

#7
While I agree this is surprising behavior and I wouldn't design an API this way, it is documented behavior. From the docs:

"in Boolean contexts, a time object is considered to be true if and only if, after converting it to minutes and subtracting utcoffset() (or 0 if that’s None), the result is non-zero"

Changing at this point would possibly break code that relied on documented library behavior. That's not a responsible thing to do.

Re: Please reconsider the Boolean evaluation of midnight

#8
post #5

Off the top of my head I can't think of a reason to check if a date exists, but I would certainly expect midnight to be truthy if I found a reason.

In Django you might have a nullable TimeField and check if it's set via "if obj.time_field".

I always write "if x is None", trying to be explicit.
Post reply on HN