SQL COALESCE() method in python

Viewed 4197

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

2 Answers

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

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)
Related