如果条件或异常执行代码块

Execute code block if condition or exception

异常是惯用语的核心Python,如果表达式的计算结果为真,是否有一种干净的方法来执行特定的代码块表达式引发异常?干净,我的意思是易于阅读,Pythonic,并且不重复代码块?

例如,而不是:

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

是否可以将其完全重写以便 report_error() 不被写入两次?

(类似问题:How can I execute same code for a condition in try block without repeating code in except clause 但这是针对特定情况,可以通过 if 语句中的简单测试来避免异常。)

是的,这个可以做得比较干净,虽然是否算得上是好的风格还是个悬而未决的问题。

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')

这来自被拒绝的想法PEP 463

lambda to the Rescue 提出了同样的想法。