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

Devin Jeanpierre jeanpierreda at gmail.com
Mon Dec 30 11:23:12 CET 2013


On Mon, Dec 30, 2013 at 12:24 AM, spir <denis.spir at gmail.com> wrote:
>
> 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].

If you, instead of raising an exception, return None or that thing,
then you can do things as so:

return foo() or bar() or baz()

This can't work if None is a reasonable value rather than just an
error value (which is often why one switches to exceptions to begin
with), but it works OK much of the time, and works OK all of the time
in some other programming languages that are built around this idiom.

-- Devin


More information about the Python-ideas mailing list