[Python-ideas] except expression

Stephen J. Turnbull stephen at xemacs.org
Thu Feb 13 05:57:56 CET 2014


Ben Finney writes:
 > Ben Finney <ben+python at benfinney.id.au> writes:
 > > Ram Rachum <ram.rachum at gmail.com> writes:

 > > > Here's an idea that would help shortening code.

Shortening code is not a win in Python in general.  Other things
equal, OK, but clarity comes first.  ITSM Raymond's comment about
simplifying *other* APIs is the right way to get support from
python-dev.

 > > > Allow a ternary expression based on except, like so:
 > > >
 > > >     first_entry = entries[0] except IndexError else None
 > > >     item = my_queue.get() except queue.Empty else None

 > > >     response_text = request('http://whatever.com').text except HttpError else "Can't access data"

Why not spell it the same way as in a try statement?

    response_text = request('http://whatever.com').text except HttpError as "can't access data"

The "as" clause would be required, so "as" always binds to the
immediately preceding "except", and iterated it should associate as
"(this except ErrorA as that) except ErrorB as other" rather than
"this except ErrorA as (that except ErrorB as other)" IMO.

I don't think it reads very well, though.  The statement form (1)
emphasizes the main operation compared to the "try", and (2) suggests
that catching an exception is quite a heavy operation compared to
execution without an exception, which is true.

 > > That is more obscure, to my eye, than laying out the control branches:

 >     try:
 >         response_text = request('http://whatever.com').text
 >     except HttpError:
 >         "Can't access data"

This has incorrect semantics.  The correct semantics would be

    try:
        response_text = request('http://whatever.com').text
    except HttpError:
        response_text = "Can't access data"

I assume.


More information about the Python-ideas mailing list