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

Stephen J. Turnbull stephen at xemacs.org
Thu Aug 20 04:31:20 CEST 2009

Jeff McAninch writes:

 > _*Very Simple Example - type coercion:
 > *_Current approach:
 >     try:
 >         x = float(string)
 >     except:
 >         x = float('nan')
 > Proposed solution using exception-based conditional expression:
 >     x = float(string) except ValueError: float('nan')


I really don't like the colon in the middle of the expression.  It
just looks like broken syntax because everywhere else in Python colon
introduces a suite.  I wonder if you really need it?

I generally don't like a general conditional expression.  For reasons
presented below, I don't think it's as flexible as think it can be.
OTOH, I fund it much less readable than the existing statement-based

 > _*Simple Example - type coercion in a list comprehension:
 > *_Current approach:
 >     def safe_float(string):
 >         try:
 >             x = float(string)
 >         except ValueError:
 >             x = float('nan')
 >         return x
 >     ...
 >     xs = (safe(float(string)) for string in strings)

I don't have a problem with the above.  But I can see that for

 > In data processing, I often string together a sequence of iterable
 > list comprehensions, corresponding to a sequence of operations on a
 > given dataset "ys" to produce a processed dataset "x":

an exception-handling clause in comprehensions (and generator
expressions?) might be useful, to make the exceptions handled
explicit.  For the cases I can imagine using myself, I would generally
prefer the approach of defining functions to handle the exceptions,
because they'd all be similar (eg, coercing exceptions to float("nan")
as above), though.

 > try-except syntax.  So the following examples would be allowed:
 >     x = expression0 except: default_expression
 >     x = expression0 except exception1: expression1 except exception2: expression2 except: default_expression

But it seems to me the ez-read interpretation of

    x = expression0 except exception1: expression1 except: default_expression


    x = expression0 except exception1: (expression1 except: default_expression)

Ie, your parser resolves the "dangling except" ambiguity in the
opposite way to the conventional resolution of the "dangling else"
ambiguity.  And what if excepts are mixed with conditional

  x = exp0 except exc1: exp1 if exp2 else exp3 except: exp4

Does the bare except bind to exp0, the if expression, or exp3?  I'm
sure you can define rules to disambiguate.  However, I suspect that it
will be hard to get agreement that any given set of rules is the
appropriate way to resolve the ambiguity.

More information about the Python-ideas mailing list