return
上下文管理器可以在处理异常时导致它所在的功能吗?
我有 try-except 模式,这对我正在编写的几种方法很常见,我希望用上下文管理器将其干燥。如果存在Exception
.
这是我当前实现的示例:
>>> class SomeError(Exception):
... pass
...
>>> def process(*args, **kwargs):
... raise SomeError
...
>>> def report_failure(error):
... print('Failed!')
...
>>> def report_success(result):
... print('Success!')
...
>>> def task_handler_with_try_except():
... try:
... result = process()
... except SomeError as error:
... report_failure(error)
... return
... # Continue processing.
... report_success(result)
...
>>> task_handler_with_try_except()
Failed!
有没有办法干燥 try-except 以便任务处理函数SomeError
在引发时返回?
注意:任务处理程序由库中的代码调用,该库不处理任务处理程序函数生成的异常。
这是一次尝试,但它会导致UnboundLocalError
:
>>> import contextlib
>>> @contextlib.contextmanager
... def handle_error(ExceptionClass):
... try:
... yield
... except ExceptionClass as error:
... report_failure(error)
... return
...
>>> def task_handler_with_context_manager():
... with handle_error(SomeError):
... result = process()
... # Continue processing.
... report_success(result)
...
>>> task_handler_with_context_manager()
Failed!
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "<input>", line 6, in task_handler_with_context_manager
UnboundLocalError: local variable 'result' referenced before assignment
是否可以使用上下文管理器来干燥这种模式,或者是否有替代方案?