[Python-ideas] PEP 505 -- None-aware operators

Franklin? Lee leewangzhong+python at gmail.com
Fri Oct 14 09:46:04 EDT 2016


On Oct 14, 2016 9:14 AM, "Gustavo Carneiro" <gjcarneiro at 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:
https://www.postgresql.org/docs/9.6/static/functions-conditional.html#FUNCTIONS-COALESCE-NVL-IFNULL
>
> 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.)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20161014/eb33ccbb/attachment-0001.html>


More information about the Python-ideas mailing list