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

Chris Angelico rosuav at gmail.com
Fri Feb 21 17:13:58 CET 2014

On Sat, Feb 22, 2014 at 2:19 AM, Brett Cannon <brett at python.org> wrote:
> I understand you are arguing that a try expression will lead to people just
> doing `something() except Exception: None` or whatever and that people will
> simply get lazy and not think about what they are doing with their
> exceptions. Unfortunately they already are; that shipped sailed when we
> didn't eliminate bare except clauses in Python 3 (hopefully we can change
> that in Python 4).

That's already come up a few times. I wrote a script to try to find
potential conversion targets, and technically it's correct to show
this up:

        compile(code, fn, 'exec')
    except SyntaxError as err:
        yield err.lineno, 'not compilable: %s' % err

Yes, technically you could treat that as an expression. Well, okay.
Current version of the proposal doesn't include 'as', so you can't do
that. Let's grab the next one.

        except Exception:
            logger.exception('Exception in callback %s %r',
                             self._callback, self._args)

That could, per PEP 463, become:
        (self._callback(*self._args) except Exception:
            logger.exception('Exception in callback %s %r',
                             self._callback, self._args))

But that would be abuse of the syntax. It's just like converting this:

for s in list_of_strings:

into an expression:

[print(s) for s in list_of_strings]

Neither of them is a good way to write code, yet that's not the fault
of either map() or the list comp.

> I'm totally fine restricting this proposal to not having any concept of
> exception catching or finally clause: it just replaces the simplest
> try/except clause possible (while requiring an exception be specified). That
> takes care of the common control flow use case of exceptions while requiring
> more thought for more complex cases.

The finally clause was never in the proposal. I added it as an open
issue early on, just to see if it gathered any interest, but the
weight of opinion agreed with my initial feeling: it's utterly useless
to the exception syntax. Same goes for an else clause. Currently, the
two complexities not possible in the expression form are capturing the
exception with 'as' (for technical reasons) and stringing multiple
except clauses on (for complexity reasons). In the standard library,
counting up all the cases that could plausibly be converted to
expression form, very very few use either feature. So this is a case
of "do just the really simple option and catch 98.5% of the actual


More information about the Python-Dev mailing list