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

Chris Rebert pyideas at rebertia.com
Thu Aug 20 12:45:31 CEST 2009

On Thu, Aug 20, 2009 at 3:15 AM, Jeff McAninch<mcaninch at lanl.gov> wrote:
> Calvin Spealman wrote:
>> -1 on colons in the expression like that. I like the idea of being
>> able to handle an exception in generator expressions and the like, but
>> I've never seen a syntax I liked. I think I've favored the idea of
>> something like `float(x) except float('nan') if ValueError` thinking
>> it reads more naturally as an expression, puts the real logic
>> ("convert x to a float or get a NaN float") together, which I think
>> makes sense.
> Yes, I agree about the colons.  They have no purpose.  I was just blindly
> following the try-except.  (Duh! on my part)
> So, in the simple example:
>  x = float(string) except ValueError float('nan')

I would feel more comfortable with another keyword in there. Perhaps:

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

Which reads like:

"x is the float value of string, except in the event of ValueError,
then it's float('nan')"

Which I find rather pleasing.

> But possibly the exception tuples now have to be explicitly tuples?
>  x = float(string) except (ValueError,) float('nan')

Yech. That doesn't look so great.

At any rate, I do seriously question the bang-for-the-buck of adding
this construct. Yes, it makes such conversions shorter, but couldn't
one just define a `float_or_nan` conversion function that defaults to
NaN in case of error to essentially the same effect?
I can see how the construct might help in comparatively
quick-and-dirty scripts, but should Python actively encourage
comparatively cavalier error-handling?


More information about the Python-ideas mailing list