2017-09-19 27 views
0

由于例外对于惯用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语句内避免异常的具体情况)

回答

0

是的,这是可以比较干净地完成,但它是否能成为认为好风格是一个悬而未决的问题。

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提出了相同的想法。