Re: [Python-ideas] PEP 505 -- None-aware operators
On Oct 14, 2016 9:14 AM, "Gustavo Carneiro"
Sorry if I missed the boat, but only just now saw this PEP.
Glancing through the PEP, I don't see mentioned anywhere the SQL
alternative of having a coalesce() function: https://www.postgresql.org/docs/9.6/static/functions-conditional.html#FUNCTI...
In Python, something like this:
def coalesce(*args): for arg in args: if arg is not None: return arg return None
Just drop it into builtins, and voila. No need for lengthy discussions
about which operator to use because IMHO it needs no operator.
Sure, it's not as sexy as a fancy new operator, nor as headline grabbing,
but it is pretty useful. 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. For example: return x?.a?.b?.c instead of: if x is None: return None if x.a is None: return None if x.a.b is None: return None return x.a.b.c You can use try-catch, but you might catch an irrelevant exception. try: return x.a.b.c except AttributeError: return None If `x` is an int, `x.a` will throw an AttributeError even though `x` is not None. A function for the above case is: def coalesce(obj, *names): for name in names: if obj is None: return None obj = getattr(obj, name) return obj return coalesce(x, 'a', 'b', 'c') See this section for some examples: https://www.python.org/dev/peps/pep-0505/#behavior-in-other-languages (The PEP might need more simple examples. The Motivating Examples are full chunks of code from real libraries, so they're full of distractions.)
participants (2)
-
Franklin? Lee
-
Gustavo Carneiro