コンテキストマネージャーは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 することは可能ですか、それとも別の方法がありますか?