我正在创建一个装饰器,它在它的目标函数中捕获一个引发的错误,并允许用户继续执行脚本(绕过函数)或退出脚本。
def catch_error(func):
"""
This decorator is used to make sure that if a decorated function breaks
in the execution of a script, the script doesn't automatically crash.
Instead, it gives you the choice to continue or gracefully exit.
"""
def caught(*args):
try:
return func(*args)
except Exception as err:
question = '\n{0} failed. Continue? (yes/no): '.format(func.func_name)
answer = raw_input(question)
if answer.lower() in ['yes','y']:
pass
else:
print " Aborting! Error that caused failure:\n"
raise err
return None
return caught
请注意,如果用户选择绕过错误返回函数并继续执行脚本,则装饰器将返回 None。这适用于只返回单个值的函数,但它会在尝试解包多个值的函数上崩溃。例如,
# Both function and decorator return single value, so works fine
one_val = decorator_works_for_this_func()
# Function nominally returns two values, but decorator only one, so this breaks script
one_val, two_val = decorator_doesnt_work_for_this_func()
有没有办法可以确定我的目标函数应该返回的值的数量?例如,类似:
def better_catch_error(func):
def caught(*args):
try:
return func(*args)
except Exception as err:
...
num_rvals = determine_num_rvals(func)
if num_rvals > 1:
return [ None for count in range(num_rvals) ]
else:
return None
return caught
与往常一样,如果有更好的方法来做这种事情,请告诉我。谢谢!
更新:
感谢所有的建议。我决定将 catch_error 的范围缩小到一个函数类,它们只返回一个字符串值。我只是将返回多个值的所有函数拆分为返回单个值的单独函数以使它们兼容。我一直希望让 catch_error 更通用(并且有一些关于如何做到这一点的有用建议),但对于我的应用程序来说这有点过头了。再次感谢。