Skip to content Skip to sidebar Skip to footer

Execute Code Block If Condition Or Exception

With exceptions being so central to idiomatic Python, is there a clean way to execute a particular code block if an expression evaluates to True or the evaluation of the expression

Solution 1:

Yes, this can be done relatively cleanly, although whether it can be considered good style is an open question.

deftest(expression, exception_list, on_exception):
    try:
        return expression()
    except exception_list:
        return on_exception

if test(lambda: some_function(data), SomeException, None) isNone:
    report_error('Something happened')

This comes from an idea in the rejected PEP 463.

lambda to the Rescue presents the same idea.

Post a Comment for "Execute Code Block If Condition Or Exception"