[Python-ideas] chained try (was Re: "maybe import"?)

spir denis.spir at gmail.com
Mon Dec 30 09:24:16 CET 2013


On 12/30/2013 01:24 AM, Nick Coghlan wrote:
> On 30 Dec 2013 08:24, "Andrew Barnert" <abarnert at yahoo.com> wrote:
>>
>> On Dec 29, 2013, at 1:41, spir <denis.spir at gmail.com> wrote:
>>
>>>> "except try" looks horrible, but I can't think of anything better.
>>>
>>> I would buy (if cheap!):
>>>
>>>     try:
>>>         stuff
>>>     else try:
>>>         other stuff
>>>     else try:
>>>         different stuff
>>>     except Exception as e:
>>>         deal with it
>>
>> The advantage of "except try" is that it leaves the door open for
> specifying only certain exceptions instead of all, which would be useful in
> some cases.
>>
>> But the advantage of "else try" is that it closes that door, eliminating
> most of the other questions I and others raised. It's clearly pure
> syntactic sugar with no ambiguity. Maybe that's a better idea.
>
> The else block triggers when no exception was thrown, so even if this idea
> was to be accepted at all (which seems unlikely), that particular spelling
> definitely wouldn't be accepted for something that only triggers when an
> exception is thrown.

I guess mean the else block in a 'normal' "try...except...else" construct? In 
this different form, there "else try", not just "else". I understood it as a 
single keyword (maybe read it elsetry, somewhat like elif) that denotes 
different semantics.

> In practice, the existing more general solution of extracting an
> appropriately named function is likely to improve readability more than
> adding a new variation on the already complex try/except/else/finally
> construct, which is why I consider it unlikely that a change along these
> lines would be accepted.

After some more reflexion, I find this general pattern of "chained try" (new 
thread title) really meaningful and useful, but maybe too rare to deserve proper 
syntax. However, what is the proper way to express it using current Python features?

Clearly, a series of nested try/except (compare: a series of nested if/else if 
python had no elif) is not the right tool, in my view, because try/except is to 
be used whenever the except branch is rare (semantically and practically, 
because itis clstly). What else?

Try/elsetry would not need to trigger actual exceptions with full error objects, 
exception catching, and stack unwinding (the whole machinary), but only set a 
plain flag meaning "this branch fails to execute normally [1].

Denis

[1] Could be a global bit or other var in the implementation, a CPU register, or 
even the carry flag in the CPU. See also: 
[https://www.lyngvig.org/%2FTeknik%2FA-Proposal-for-Exception-Handling-in-C]


More information about the Python-ideas mailing list