Skip to content

Instantly share code, notes, and snippets.

@SyraD
Forked from GuilhermeHideki/coalesce.py
Last active November 26, 2018 12:25
Show Gist options
  • Save SyraD/632cdbdf9cf52d77ecfb352bd697acb2 to your computer and use it in GitHub Desktop.
Save SyraD/632cdbdf9cf52d77ecfb352bd697acb2 to your computer and use it in GitHub Desktop.
Python coalesce
def coalesce(*args):
"""Returns the first not None/Empty/False item. Similar to ?? in C#.
It's different from a or b, where false values are invalid.
:param args: list of items for checking
:return the first not None item, or None
"""
out = None #default return value
for arg in args:
if arg: #find first non-falsey argument
out = arg
break #short circuit, stop checking at first truthy
return out
assert ( coalesce(None, '', '', 'test') == 'test')
assert ( coalesce(None, 'test') == 'test')
assert ( coalesce(1, 'test') == 1)
assert ( coalesce('test', None ) == 'test')
assert ( coalesce('test', '' ) == 'test')
assert ( coalesce('test', None, '') == 'test')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment