No, context managers can't do that, since you can only return
from a function within its body.
However, what you're looking for does exist! It's called a decorator.
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)
Note that if you always want to report_success
too, you can DRY this up even more!
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()
You don't even need task handler at all anymore:
@report_all
def process():
# ...