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

Alexander Kozlovsky alexander.kozlovsky at gmail.com
Sat Aug 15 00:41:30 CEST 2009

Jeff McAninch wrote:
> I very often want something like a try-except conditional expression similar
> to the if-else conditional. 

I think it may be done currently with the help of next function:

    def guard(func, *args):
            return func()
        except Exception, e:
            for exc_type, exc_func in args:
                if isinstance(e, exc_type):
                    return exc_func()

Example usage:

    a, b, c = 10, 20, 0

    result = a + b/c  # raise ZeroDivisionError

    result = a + guard(lambda: b/c, (TypeError, lambda: 10),
                                    (ZeroDivisionError, lambda: b/2))
May be not very concise, but it works...

Best regards,
 Alexander                  mailto:alexander.kozlovsky at gmail.com

More information about the Python-Dev mailing list