[Python-Dev] (try-except) conditional expression similar to (if-else) conditional (PEP 308)

Raymond Hettinger python at rcn.com
Thu Aug 6 02:59:44 CEST 2009

[Jeffrey E. McAninch, PhD]
> I very often want something like a try-except conditional expression similar
> to the if-else conditional.  
> An example of the proposed syntax might be:
>    x = float(string) except float('nan')
> or possibly
>    x = float(string) except ValueError float('nan')

I've long wanted something like this.
One possible spelling is:

   x = float(string) except ValueError else float('nan')

If accepted, this would also solve the feature requests for various functions to have default arguments.
For example:

   x = min(seq) except ValueError else 0     # default to zero for empty sequences

It would also be helpful in calculations that have algebraic restrictions:

  sample_std_deviation = sqrt(sum(x - mu for x in seq) / (len(seq)-1)) except ZeroDivisionError else float('Inf')


More information about the Python-Dev mailing list