I ran into some code recently that was checking datetime objects and figured it could be cleaned up a little:
# original
if (datetime1 and (datetime2 is None)):
do_things()
# slightly cleaner version
if (datetime1 and not datetime2):
do_things()
But I realized that these two statements are not quite equal IF there is a valid datetime object that evaluates as False. For example:
if not '':
print('beep')
else:
print('boop')
# output: beep
if '' is None:
print('beep')
else:
print('boop')
# output: boop
Upon looking for information about the boolean value of datetime/time/date objects in Python, I came up empty. Does anyone know how Python handles this? And if I run into a similar problem with a different object type, is there a reliable way to check when its boolean value is true or false?
Unless the class implements a
__bool__()or__len__()method that customizes it, all class instances are truthy by default. If__bool__()is defined, it's used. If not, the defaultobject.__bool__()calls__len__(); if it returns non-zero, the object is truthy.The
datetime.datetimeclass doesn't have such either method, so all datetime objects are truthy. So your transformation is valid.This is documented at
object.__bool__():