pythonpython-datetimetruthiness

Can python date/time/datetime objects have a boolean value of False?


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?


Solution

  • 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 default object.__bool__() calls __len__(); if it returns non-zero, the object is truthy.

    The datetime.datetime class doesn't have such either method, so all datetime objects are truthy. So your transformation is valid.

    This is documented at object.__bool__():

    Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __bool__(), all its instances are considered true.