次のコードを検討してください。
class Test(object):
def __enter__(self):
pass
def __exit__(self,type,value,trace):
if type:
print "Error occured: " + str(value.args)
#if I changed the next line to 'return True', the
#'print "should not happen"' statements are executed, but the
#error information would be only printed once (what I want)
return False
return True
with Test():
with Test():
with Test():
raise Exception('Foo','Bar')
print "should not happen"
print "should not happen"
例の出力:
エラーが発生しました: ('Foo', 'Bar')
エラーが発生しました: ('Foo', 'Bar')
エラーが発生しました: ('Foo', 'Bar')
ネストされたステートメントがいくつwith
かあり、コードのどこかで例外が発生した場合を処理したいと考えています。私が達成したいのは、実行が停止されることです(上記の例では「発生しないはずです」という出力はありません)が、エラー情報は一度だけ出力されます。したがって、同じエラーが既に処理されているかどうかを何らかの形で知る必要があります。
これをどのように達成できるか考えていますか?