Add None coalescing operator in Python

To add another angle to the discussion:

I’m not sure whether the discussions have already mentioned this (the PEP 505 doesn’t list this), but SQL has a function called COALESCE(), which is commonly used for handling NULL values: see e.g. the PostgreSQL docs: PostgreSQL: Documentation: 16: 9.18. Conditional Expressions

Making this a builtin in Python would solve many of the situations listed in PEP 505 in an explicit and elegant way.

The function would also go beyond just checking one value for None. It returns the first non-None argument, so you don’t have to chain operators and you can use the builtin in a functional way with iterators.

Furthermore, we could optionally extend this to also accept N/A values (math.isnan()), empty strings, empty lists/tuples, etc. to address other areas where “this value is not available/usable” pops up. Here’s a sketch:

coalesce(*args, /, check=None, logic=False)

Return the first value from args which is not the check object (defaults to None). If check is a callable, return the first value from args which check(value) is False. logic may be set to True, to swap the test logic.

We could then add a few handy operators for the check function, e.g.

  • tuple.isempty() - check for empty tuples
  • list.isempty() - check for empty tuples
  • str.isempty() - check for empty strings
  • etc.
    or a more generic isemtpy() function, which check the length and the type of an object.

Other functions which come in handy as check function:

  • math.isnan()
  • math.isfinite(), with logic set to True
  • math.isinf()
  • len()
  • bool()
  • operator.attrgetter()
  • operator.itemgetter()
  • cmath.isnan()
7 Likes