2

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

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

4

1 回答 1

2

不,上下文管理器不能这样做,因为你只能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():
    # ...
于 2014-05-04T17:46:19.447 回答