处理异常时,上下文管理器能否将其所在的功能引入return

我有试写除外模式,这对我正在编写的几种方法很常见,我希望使用上下文管理器将其干燥。如果存在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


是否可以使用上下文管理器来干燥此模式,或者有替代方法吗?

最佳答案

不可以,上下文管理器无法做到这一点,因为您只能从函数体内的return进行操作。

但是,您要找的东西确实存在!它称为装饰器。

def handle_errors(func):
    def inner(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except SomeError as error:
            report_failure(error)
            return
    return inner

@handle_errors
def task_handler():
    result = process()
    report_success(result)




请注意,如果您始终也想report_success,则可以将其干燥得更多!

def report_all(func):
    def inner(*args, **kwargs):
        try:
            ret = func(*args, **kwargs)
            report_success(ret)
            return ret
        except SomeError as error:
            report_failure(error)
            return
    return inner

@report_all
def task_handler():
    return = process()


您甚至不再需要任务处理程序:

@report_all
def process():
    # ...

关于python - 从父函数返回而不会引发异常的上下文管理器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23459447/

10-12 04:19