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

Antoine Pitrou solipsis at pitrou.net
Thu Aug 6 13:32:16 CEST 2009


Raymond Hettinger <python <at> rcn.com> writes:
> 
> For example:
> 
>    x = min(seq) except ValueError else 0     # default to zero for empty
sequences

How about:
    x = min(seq) if seq else 0

Shorter and more readable ("except X else Y" isn't very logical).

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

Same transformation here.

I have to say that the original example:
    x = float(string) except ValueError else float('nan')

looks artificial. I don't see how it's adequate behaviour to return a NaN when
presented with a string which doesn't represent a float number.

Besides, all this is python-ideas material (and has probably already been
proposed before).

Regards

Antoine.




More information about the Python-Dev mailing list