问题
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