执行代码块如果条件或异常 [英] Execute code block if condition or exception
问题描述
例如,而不是:
try:
如果some_function(data)为None:
report_error('Something happen')
除了SomeException:
report_error('Something occurred')#重复代码
可以将其彻底重写,以便 report_error()
不写两次?
(类似的问题:如何在try块中执行相同的代码,在except子句中重复代码,但这是针对特定情况,通过if语句中的简单测试可以避免异常。)
是的,这可以做得比较干净,尽管它可以被认为是好的风格是开放的sti。
def test(expression,exception_list,on_exception):
try:
return expression()
除了exception_list:
return on_exception
如果test(lambda:some_function(data),SomeException,None)是None:
report_error('Something happen')
这来自拒绝的一个想法 PEP 463 。
lambda到Rescue 呈现相同的想法。
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.)
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.
这篇关于执行代码块如果条件或异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!