[Python-Dev] PEP 463: Exception-catching expressions

Stefan Behnel stefan_ml at behnel.de
Sun Feb 23 19:51:43 CET 2014


Chris Angelico, 21.02.2014 04:15:
> Just as PEP 308 introduced a means of value-based conditions in an
> expression, this system allows exception-based conditions to be used
> as part of an expression.
> [...]
> This currently works::
> 
>     lst = [1, 2, None, 3]
>     value = lst[2] or "No value"
> 
> The proposal adds this::
> 
>     lst = [1, 2]
>     value = lst[2] except IndexError: "No value"

I see a risk of interfering with in-place assignment operators, e.g.

    x /= y except ZeroDivisionError: 1

might not do what one could expect, because (as I assume) it would behave
differently from

    x = x / y except ZeroDivisionError: 1

I think that falls under the "overly broad exception handling" issue. If
you want to include the assignment, you'll have to spell out the try-except
block yourself. I find the difference in the two behaviours very
unfortunate, though.

This also reduces the scope of applicability somewhat. Cython has typed
assignments, so a straight forward idea would be to handle TypeErrors in
assignments like this:

    cdef str s
    s = x except TypeError: str(x)

However, I guess that would similarly counter the idea of exception
handling in an *expression*, and the correct and non-ambiguous way to do
this would be to spell out the try-except block.

Summing it up, my impression is that it helps some use cases but leaves
others more ambiguous/unclear/unfortunate, which makes me lean towards
rejecting it.

Stefan




More information about the Python-Dev mailing list