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 を DRY して、発生した場合にタスク ハンドラ関数が返されるようにする方法はありますSomeErrorか?

注:タスク ハンドラーは、タスク ハンドラー関数から生成された例外を処理しないライブラリ内のコードによって呼び出されています。

これは 1 つの試行ですが、次の原因になります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

コンテキスト マネージャを使用してこのパターンを DRY することは可能ですか、それとも別の方法がありますか?

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 に答える