2

How could I recreate the COALESCE() method from SQL, but in python?

rachelalll
  • 92
  • 2
  • 5
  • I think [this](https://stackoverflow.com/questions/4978738/is-there-a-python-equivalent-of-the-c-sharp-null-coalescing-operator) may answer your question. – Yosua Apr 10 '20 at 15:37

2 Answers2

3

You can use or, in which your expression will be equal to the first logical True:

var = 1
res = var or 2 # res=1

var = None
res = var or 1 # res=1
Gabio
  • 8,225
  • 3
  • 8
  • 26
1

COALESCE is a variadic function, so you need a little more than just Python's or:

def coalesce(iterable):
    for el in iterable:
        if el is not None:
            return el
    return None

This assumes that Python's None is the equivalent of SQL's NULL.

More compactly, you could adapt the first_true() "recipe" from the itertools documentation:

def coalesce(iterable):
    return next((el for el in iterable if el is not None), None)
pilcrow
  • 54,181
  • 12
  • 87
  • 133