[Python-ideas] One-line "try with" statement

Bruce Leban bruce at leapyear.org
Sun Mar 3 23:31:29 CET 2013


On Sat, Mar 2, 2013 at 2:45 PM, Alan Johnson <alan at breakrs.com> wrote:

>
>         try with context_manager():
>                 … bunch of code …
>         except:
>                 … exception handler …



This optimization saves a colon and some white space and mixes two
unrelated concepts.

The try/except pattern I want to optimize is

    try:
        x = expr1
    except ValueError:
        x = expr2

For example:

    expr1 except ValueError else expr2
or
    try expr1 except ValueError else expr2

This is particularly useful in cases like this:

    a = ((try t.x except AttributeError else 0)
         + (try t.y except AttributeError else 0)
         + (try t.z except AttributeError else 0))

where standard try/except requires 13 lines and is much harder to read.

Yes, this can be done with a function and two lambdas (and I've done it
this way):

    try_except(lambda: expr1, ValueError, lambda: expr2)

    def try_except(value, exceptions, otherwise):
        try:
            return value()
        except exceptions or Exception:
            return otherwise()

--- Bruce
Learn how hackers think: http://j.mp/gruyere-security
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130303/2e47b6cb/attachment.html>


More information about the Python-ideas mailing list