[Python-ideas] Inline 'raises' expression

Collin Winter collinw at gmail.com
Sat Aug 30 04:50:35 CEST 2008


On Sun, Aug 24, 2008 at 3:43 AM, Fredrik Johansson
<fredrik.johansson at gmail.com> wrote:
> It happens that I'm just interested in whether an expression raises an
> exception, not the return value. This might look something like
>
>    try:
>        check_status()
>    except IOError:
>        cleanup()
>
> which could be written more simply as
>
>    if check_status() raises IOError:
>        cleanup()

If you need to add handling for another type of exception, you have to
totally restructure your code. It's no longer a matter of adding
another except statement to the chain.

Also, what do you do if you need to use the exception instance? Are
you proposing (by implication) the additional syntax "if
check_status() raises IOError as foo:"? What If I want multiple
statements to be guarded by the try block? Again, I have to switch
mechanisms.

> Also, instead of the inconvenient
>
>    self.assertRaises(ZeroDivisionError, lambda: 1/0)
>
> one could just write
>
>    assert 1/0 raises ZeroDivisionError

I rarely find myself only caring about the type of the exception. For
anything complex, I want to make some assertion about the
attributes/structure of the raised exception, for example, regexing
the exception's str() value. If I want to change from only caring
about the type of the exception (the syntax you propose above) to
caring about the contents/structure of the exception instance, I have
to completely change which mechanism I'm using.

With this proposal I can't gracefully go from doing something simple
to doing something complex. -1

Collin Winter



More information about the Python-ideas mailing list