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

ilya ilya.nikokoshev at gmail.com
Thu Aug 6 14:03:12 CEST 2009


I took a look at the options 1 and 2:

    x = float(string) except float('nan') if ValueError
    y = float(string) except ValueError: float('nan')

and I think this can be done just as easily with existing syntax:

    x = try_1(float, string, except_ = float('nan'), if_ = ValueError)
    y = try_2(float, string, { ValueError: float('nan') })

Here's the full example:

----- example starts -----

def try_1(func, *args, except_ = None, if_ = None):
    try:
        return func(*args)
    except if_ as e:
        return except_

def try_2(func, *args):
    'The last argument is a dictionary {exception type: return value}.'
    dic = args[-1]
    try:
        return func(*args[:-1])
    except Exception as e:
        for k,v in dic.items():
            if isinstance(e, k):
                return v
        raise

for string in ['5', 'five']:
    #   x = float(string) except float('nan') if ValueError
    x = try_1(float, string, except_ = float('nan'), if_ = ValueError)
    #   y = float(string) except ValueError: float('nan')
    y = try_2(float, string, { ValueError: float('nan') })
    print(x, y)

----- example ends -----

As a side note, if I just subscribed to python-dev, is it possible to
quote an old email? Below is my manual cut-and-paste quote:

---------- my quote --------------

Nick Coghlan wrote:
> P.J. Eby wrote:
>> At 05:59 PM 8/5/2009 -0700, Raymond Hettinger wrote:
>>> [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')
>>> +1 I've long wanted something like this.
>>> One possible spelling is:
>>>
>>>   x = float(string) except ValueError else float('nan')
>> I think 'as' would be better than 'else', since 'else' has a different
>> meaning in try/except statements, e.g.:
>>
>>    x = float(string) except ValueError, TypeError as float('nan')
>>
>> Of course, this is a different meaning of 'as', too, but it's not "as"
>> contradictory, IMO...  ;-)
>
> (We're probably well into python-ideas territory at this point, but I'll
> keep things where the thread started for now)
>
> The basic idea appears sound to me as well. I suspect finding an
> acceptable syntax is going to be the sticking point.
>
> Breaking the problem down, we have three things we want to separate:
>
> 1. The expression that may raise the exception
> 2. The expression defining the exceptions to be caught
> 3. The expression to be used if the exception actually is caught
>
>>From there it is possible to come up with all sorts of variants.
>
> Option 1:
>
> Change the relative order of the clauses by putting the exception
> definition last:
>
>   x = float(string) except float('nan') if ValueError
>   op(float(string) except float('nan') if ValueError)
>
> I actually like this one (that's why I listed it first). It gets the
> clauses out of order relative to the statement, but the meaning still
> seems pretty obvious to me.
>
A further extension (if we need it):

     result = foo(arg) except float('inf') if ZeroDivisionError else
float('nan')

The 'else' part handles any other exceptions (not necessarily a good idea!).

or:

     result = foo(arg) except float('inf') if ZeroDivisionError else
float('nan') if ValueError

Handles a number of different exceptions.

> Option 2:
>
> Follow the lamba model and allow a colon inside this form of expression:
>
>   x = float(string) except ValueError: float('nan')
>   op(float(string) except ValueError: float('nan'))
>
> This has the virtue of closely matching the statement syntax, but
> embedding colons inside expressions is somewhat ugly. Yes, lambda
> already does it, but lambda can hardly be put forward as a paragon of
> beauty.
>
A colon is also used in a dict literal.

> Option 3a/3b:
>
> Raymond's except-else suggestion:
>
>   x = float(string) except ValueError else float('nan')
>   op(float(string) except ValueError else float('nan'))
>
[snip]
-1


More information about the Python-Dev mailing list