VocalBit« assorted thoughts on technology, computers and programming »

An Except-Assign statement for Python

A syntax proposal for Python that describes how an 'except' operator would work.

Often I find myself wanting to wrap small bits of code in a try/except block. When only one line is wrapped, the nested block for try seems like an overkill:

    f = open('file.txt')
except IOError, err:
    return 'could not open'
# do something with f

I want to propose an except operator which would wrap an expression with an implicit try. You would use it like this:

f, err = open('file.txt') except IOError
if err:
   return 'could not open'

This is not just easier to type, but much easier to read. Notice the expression on the first line returns a tuple. If an IOError is thrown by open(), it will be assigned to err and f will be None. If no exception is thrown, f will hold the result of open() and err will be None.

Here are the exact semantics:

result, err = <expr> except <Exception>

# the above is equivalent to:

    result = <expr>
    err = None
except <Exception> as err:
    result = None

Note that the usual try/catch syntax will continue to work and the shorter except clause syntax can be used in some cases where it simplifies the code. What do you think? Is there something similar already available in other languages?