<p dir="ltr">On Oct 14, 2016 9:14 AM, "Gustavo Carneiro" <<a href="mailto:gjcarneiro@gmail.com">gjcarneiro@gmail.com</a>> wrote:<br>
><br>
> Sorry if I missed the boat, but only just now saw this PEP.<br>
><br>
> Glancing through the PEP, I don't see mentioned anywhere the SQL alternative of having a coalesce() function: <a href="https://www.postgresql.org/docs/9.6/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL">https://www.postgresql.org/docs/9.6/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL</a><br>
><br>
> In Python, something like this:<br>
><br>
> def coalesce(*args):<br>
> for arg in args:<br>
> if arg is not None:<br>
> return arg<br>
> return None<br>
><br>
> Just drop it into builtins, and voila. No need for lengthy discussions about which operator to use because IMHO it needs no operator.<br>
><br>
> Sure, it's not as sexy as a fancy new operator, nor as headline grabbing, but it is pretty useful.</p>
<p dir="ltr">That function is for a different purpose. It selects the first non-null value from a flat collection. The coalesce operators are for traveling down a reference tree, and shortcutting out without an exception if the path ends.</p>
<p dir="ltr">For example:<br>
return x?.a?.b?.c<br>
instead of:<br>
if x is None: return None<br>
if x.a is None: return None<br>
if x.a.b is None: return None<br>
return x.a.b.c</p>
<p dir="ltr">You can use try-catch, but you might catch an irrelevant exception.<br>
try:<br>
return x.a.b.c<br>
except AttributeError:<br>
return None<br>
If `x` is an int, `x.a` will throw an AttributeError even though `x` is not None.</p>
<p dir="ltr">A function for the above case is:<br>
def coalesce(obj, *names):<br>
for name in names:<br>
if obj is None:<br>
return None<br>
obj = getattr(obj, name)<br>
return obj</p>
<p dir="ltr"> return coalesce(x, 'a', 'b', 'c')</p>
<p dir="ltr">See this section for some examples:<br>
<a href="https://www.python.org/dev/peps/pep-0505/#behavior-in-other-languages">https://www.python.org/dev/peps/pep-0505/#behavior-in-other-languages</a></p>
<p dir="ltr">(The PEP might need more simple examples. The Motivating Examples are full chunks of code from real libraries, so they're full of distractions.)</p>