On Mon, Sep 12, 2016 at 1:05 AM, Michel Desmoulin
<desmoulinmic...@gmail.com> wrote:
> There is also an alternative to this operator, and it's allowing a
> shortcut to do:
>
> try:
>     val = do_thing()
> except ThingError:
>     val = "default"
>
> In the form of:
>
> val = do_thing() except ThingError: "default"

Note that there's a subtle difference here when multiple lookups are
involved.  Given:

    def f(spam):
        return spam().eggs().ham

With null-coalescing:

    def f(spam):
        return spam()?.eggs()?.ham

This is roughly equivalent to:

   def f(spam):
        _spam = spam()
        try:
            eggs = _spam.eggs
        except AttributeError:
            return None
        _eggs = eggs()
        try:
            return _eggs.ham
        except AttributeError:
            return None

With PEP 463 it doesn't work out so well.  The "obvious" spelling would be:

    def f(spam):
        return (spam().eggs().ham except AttributeError: None)

This is roughly equivalent to:

    def f(spam):
        try:
            return spam().eggs().ham
        except AttributeError:
            return None

Note how it's different. For one thing, it could mask AttributeError
coming from the calls.  For another, you no longer explicitly identify
which lookups to handle.  I would expect both to lead to subtle bugs,
whereas with null-coalescing you don't have those problems.

-eric
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to