[Python-3000] Exception Expressions

Calvin Spealman ironfroggy at gmail.com
Thu Aug 31 19:42:57 CEST 2006


I thought I felt in the mood for some abuse today, so I'm proposing
something sure to give me plenty of crap, but maybe someone will enjoy
the idea, anyway. This is a step beyond the recently added conditional
expressions. I actually made this up as a joke, explaining at which
point we would have gone too far with branching logic in an
expression. After making the joke, I was sad to realize I didn't mind
the idea and thought I'd see if anyone else doesn't mind it either.

    expr1 except expr2 if exc_type

For example, given a list, letters, of ['a', 'b', 'c'], we would be
able to do the following:

    print letters[7] except "N/A" if IndexError

This would translate to something along the lines of:

    try:
        _tmp = letters[7]
    except IndexError:
        _tmp = "N/A"
    print _tmp

Obviously, the except in an expression has to take precedence over if
expressions, otherwise it would evaluate '"N/A" if IndexError" first.
The syntax can be extended in some ways, to allow for handling
multiple exception types for one result or different results for
different exception types:

    foo() except "Bar or Baz!?" if BarError, BazError
    foo() except "Bar!" if BarError, "Baz!" if BazError

Other example use cases:

    # Fallback on an alternative path
    open(filename) except open(filename2) if IOError

    # Handle divide-by-zero
    while expr != "quit":
        print eval(expr) except "Can not divide by zero!" if ZeroDivisionError
        expr = raw_input()

    # Use a cache when an external resource timesout
    db.get(key) except cache.get(key) if TimeoutError

Only very basic exception handling would be useful with this syntax,
so nothing would ever get out of hand, unless someone wasn't caring
about their code looking good and keeping good line lengths, so their
code probably wouldn't look great to begin with.

If there is any positive response I'll write up a PEP.


More information about the Python-3000 mailing list