On Oct 14, 2016 9:14 AM, "Gustavo Carneiro" <gjcarne...@gmail.com> wrote:
> 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:
> 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

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.
        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

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:

(The PEP might need more simple examples. The Motivating Examples are full
chunks of code from real libraries, so they're full of distractions.)
Python-ideas mailing list
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to