[Python-ideas] exception based conditional expression, similar to if-else conditional expression

Steven D'Aprano steve at pearwood.info
Thu Aug 20 16:46:38 CEST 2009

On Fri, 21 Aug 2009 12:27:26 am Jeff McAninch wrote:

> Python's list of compound statements is pretty thin (just 7),
> and 4 of these already have expression forms.
>     for     ==> list comprehension, iterator expression
>     while   ==> list comprehension, iterator
>     if      ==> if-else conditional expression

But that one is ugly (that is, I don't think anyone *likes* the syntax, 
it's just considered the least worst), and some of us consider that its 
usefulness is dubious, or at least weak. I think the main reason that 
Python has a ternary if statement is to stop people writing the 

cond and x or y

as a short-circuit ternary if.

>     def     ==> already have lambda expressions
>     try     ==> my proposal
>     class   ==> Okay, so this one doesn't have a compound statement,
>                    but where would you use it?

But it does have a function:

>>> type("MyClass", (object,), {})
<class '__main__.MyClass'>

Or rather, class is syntactic sugar for the type known as type(), which 
isn't actually a function, but you call it as if it were one.

>     with    ==> I haven't had an occasion to use with,
>                    so can't think of an example where it could
>                    be useful as a compound expression.
> Seems to me try-except is kind of sticking out here, and I've
> tried to show what I think are natural and common places where
> a try-except expression would be appropriate.

At the moment, I would vote:

-0 for the general idea
-1 if it allows a bare except

I could possibly be convinced to change my first vote to +0 if I could 
see some real examples of code where this would be useful. (However, I 
don't think there's any power in the universe which could convince me 
that allowing bare excepts here was a good thing :)

Has anyone considered binding to an exception instance? E.g:

    x = f(x) except (ValueError, TypeError) as e: extract_from(e)

Steven D'Aprano

More information about the Python-ideas mailing list