4

If you have a value: Optional[X], a common way to check if it is None is by by using the pattern:

from typing import Optional

def some_function(value: Optional[str]):
    if not value:
        print("oopsie! value is either None or the empty string")
        return
    ...  # now you know that value is not empty

The gotcha with this pattern is other values that evaluate to False, e.g.:

  • X == str: ""
  • X == int: 0
  • X == float: 0.0 ... interestingly, bool(float('nan')) is True
  • X == list: [] (similar for sets, tuples, dicts, or other iterables)

My question is: Does any datetime.datetime object evaluate to False? Any datetime.time / datetime.date?

Martin Thoma
  • 91,837
  • 114
  • 489
  • 768
  • 2
    More accurately, each of the values you list evaluate as "falsy", not `None`. `None` is also "falsy". See https://stackoverflow.com/questions/39983695/what-is-truthy-and-falsy-how-is-it-different-from-true-and-false for an explanation. – Code-Apprentice Mar 17 '21 at 16:45
  • 1
    @Code-Apprentice Thank you, that was a typo. I fixed it in the question :-) – Martin Thoma Mar 17 '21 at 16:49

1 Answers1

4

Checking the source code for datetime, we see that it does not override __bool__(). Therefore the only "falsey" value for a variable with type Optional[datetime] object is None.

Code-Apprentice
  • 69,701
  • 17
  • 115
  • 226
  • Nice! Thank you for also pointing me to the source! I'll accept in 7 minutes (as soon as I can :-) ) – Martin Thoma Mar 17 '21 at 16:52
  • 2
    You've linked to the Python implementation, but most of that gets overwritten by `from _datetime import *` near the end. The implementation that matters for most cases is the C implementation, [which also doesn't override `__bool__`](https://github.com/python/cpython/blob/v3.9.2/Modules/_datetimemodule.c#L6431). – user2357112 supports Monica Mar 17 '21 at 16:54
  • 2
    (A timedelta *can* be falsy, though.) – user2357112 supports Monica Mar 17 '21 at 16:56
  • @user2357112supportsMonica Thanks for the link to the C source. I didn't consider that since I found the Python code. – Code-Apprentice Mar 17 '21 at 17:14
  • Those classes also do not define `__len__` - https://docs.python.org/3/reference/datamodel.html#object.__bool__. – wwii Mar 17 '21 at 17:15