如何简化Python代码:内部函数失败时让外部函数终止返回False?
问题描述
现有如下代码,其中all()函数通过为每个内部函数a()、b()、c()添加try-except逻辑,实现了任一内部函数抛出异常时,打印“finished due to error”并返回False,输出符合预期:
def a(test): if test > 1: raise Exception("error in 'a'") print("nothing happened") def b(test): if test > 1: raise Exception("error in 'b'") print("nothing happened") def c(test): if test > 1: raise Exception("error in 'c'") print("nothing happened") def all(): try: a(1) except Exception: print("finished due to error") return False try: b(2) except Exception: print("finished due to error") return False try: c(1) except Exception: print("finished due to error") return False if __name__ == "__main__": all()
该代码的输出为:
nothing happened finished due to error
现在希望修改内部函数,使all()函数可以简化为如下形式,无需为每个内部函数添加try-except逻辑,同时实现相同效果:当任一内部函数失败时,all()函数终止并返回False,输出与第一个示例一致:
def all(): a(1) b(2) c(1)
当前直接调用内部函数的all()会抛出异常并输出错误栈,无法达到预期效果,请问如何实现?
解决方案
我们可以通过装饰器统一为内部函数添加异常处理逻辑,既不用修改函数核心代码,又能让all()保持极简写法,同时实现原有的功能。
实现步骤
- 定义一个装饰器,负责捕获函数执行时的异常,打印指定提示信息,并返回执行状态(成功返回
True,失败返回False)。 - 用这个装饰器修饰
a()、b()、c()三个内部函数。 - 利用Python的
and短路特性,让all()函数通过连续调用实现“任一失败则终止并返回False”的逻辑。
完整代码
def handle_exception(func): def wrapper(*args, **kwargs): try: # 执行原函数逻辑 func(*args, **kwargs) return True except Exception: # 捕获异常时打印提示并返回失败状态 print("finished due to error") return False return wrapper @handle_exception def a(test): if test > 1: raise Exception("error in 'a'") print("nothing happened") @handle_exception def b(test): if test > 1: raise Exception("error in 'b'") print("nothing happened") @handle_exception def c(test): if test > 1: raise Exception("error in 'c'") print("nothing happened") def all(): # 利用and短路:只要前一个函数返回False,后续函数不会执行 return a(1) and b(2) and c(1) if __name__ == "__main__": all()
效果验证
运行上述代码,输出与原示例完全一致:
nothing happened finished due to error
当任一内部函数执行失败时,装饰器会立即打印提示并返回False,and的短路特性会终止后续函数的调用,最终all()返回False,完全符合需求。
内容的提问来源于stack exchange,提问作者Matias Eiletz
相关产品推荐
相关产品推荐

