Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Pure Python coalesce alternative.
class Unset:
This class represent an unset instance.
unset = Unset()
def first_or_default(sequence, condition=unset, default=None):
Returns the first or default value that matches with a condition.
sequence = iter(sequence) if condition is unset else filter(condition, sequence)
return next(sequence)
except StopIteration:
return default
def coalesce(*sequence, default=None):
Returns the first valid element in sequence.
return first_or_default(sequence, None, default=default)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment