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

Jim J. Jewett jimjjewett at gmail.com
Tue Feb 25 01:27:44 CET 2014

Greg Ewing suggested:

>> This version might be more readable:
>>     value = lst[2] except "No value" if IndexError

Ethan Furman asked:

> It does read nicely, and is fine for the single, non-nested, case
> (which is probably the vast majority), but how would
> it handle nested exceptions?

With parentheses.

Sometimes, the parentheses will make a complex expression ugly.
Sometimes, a complex expression should really be factored into pieces anyway.

Hopefully, these times are highly correlated.

The above syntax does lend itself somewhat naturally
to multiple *short* except clauses:

    value = (lst[2]
               except "No value" if IndexError
               except "Bad Input" if TypeError)

and nested exception expressions are at least possible, but deservedly ugly:

    value = (lvl1[name]
              except (lvl2[name]
                       except (compute_new_answer(name)
                                 except None if AppValueError)
                       if KeyError)
              if KeyError)

This also makes me wonder whether the cost of a subscope 
(for exception capture) could be limited to when an
exception actually occurs, and whether that might lower
the cost enough to make the it a good tradeoff.

    def myfunc1(a, b, e):
        assert "main scope e value" == e
    e = "main scope e value"
    value = (myfunc1(val1, val2, e)
              except e.reason if AppError as e)
    assert "main scope e value" == e



If there are still threading problems with my replies, please 
email me with details, so that I can try to resolve them.  -jJ

More information about the Python-Dev mailing list