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

Mike Meyer mwm-keyword-python.b4bdba at mired.org
Fri Aug 7 09:21:20 CEST 2009


On Fri, 07 Aug 2009 08:30:14 +0200
Georg Brandl <g.brandl at gmx.net> wrote:

> MRAB schrieb:
> > Jan Kaliszewski wrote:
> >>> Syntax Ideas:
> >>>     Option 1:
> >>>         x = float(string) except float('nan') if ValueError
> >>>         op(float(string) except float('nan') if ValueError)
> >> 
> >> -0.5
> >> I wouldn't mix up 'if' word with 'except' -- there are different concepts.
> >> 
> >>>     Option 2:
> >>>         x = float(string) except ValueError: float('nan')
> >>>         op(float(string) except ValueError: float('nan'))
> >> 
> >> +0.5
> >> IMHO seems to be the best of the propositions. I'd add to it optional
> >> as (like in present 'try:... except Exc as exc:...')
> >> 
> > Can there be multiple 'except's?
> > 
> >      reciprocal = 1.0 / float(string) except ValueError: float('nan') 
> > except ZeroDivisionError: float('inf')
> 
> Don't over-complicate.  This proposal has a slim chance of success as it
> is; piling on top isn't going to help.

Assuming you avoid the ':' version, shouldn't multiple excepts fall
out of the grammar naturally?

x = ((1.0 / float(string)
      except float('nan') if ValueError)
     except float('inf') if ZeroDivisionError)

parses as "expr1 except float('inf') if ValueError", where expr1 is 
"(1.0 / float(string) except float('nan') if ValueError)".

Yes, it's as ugly as nesting if/else expressions, but those work, so
these should.

FWIW, I'm +.5 on this. I don't see a lot of use for it, but can see
that where it is useful, it's easier to read than a try:/except:.

     <mike
-- 
Mike Meyer <mwm at mired.org>		http://www.mired.org/consulting.html
Independent Network/Unix/Perforce consultant, email for more information.

O< ascii ribbon campaign - stop html mail - www.asciiribbon.org



More information about the Python-ideas mailing list