Execute code block if condition or exception

社会主义新天地 提交于 2019-12-24 18:45:59

问题


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 raises an exception? By clean, I mean an easy-to-read, Pythonic, and not repeating the code block?

For example, instead of:

try:
    if some_function(data) is None:
        report_error('Something happened')
except SomeException:
    report_error('Something happened') # repeated code

can this be cleanly rewritten so that report_error() isn't written twice?

(Similar question: How can I execute same code for a condition in try block without repeating code in except clause but this is for a specific case where the exception can be avoided by a simple test within the if statement.)


回答1:


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

def test(expression, exception_list, on_exception):
    try:
        return expression()
    except exception_list:
        return on_exception

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

This comes from an idea in the rejected PEP 463.

lambda to the Rescue presents the same idea.



来源:https://stackoverflow.com/questions/46304716/execute-code-block-if-condition-or-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!