__enter__()
に例外があっても__exit__()
メソッドが呼び出されることはありますか?コンテキストマネージャーで例外をキャッチする__enter __()
>>> class TstContx(object):
... def __enter__(self):
... raise Exception('Oops in __enter__')
...
... def __exit__(self, e_typ, e_val, trcbak):
... print "This isn't running"
...
>>> with TstContx():
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __enter__
Exception: Oops in __enter__
>>>
編集
これは...後肢の光景で
class TstContx(object):
def __enter__(self):
try:
# __enter__ code
except Exception as e
self.init_exc = e
return self
def __exit__(self, e_typ, e_val, trcbak):
if all((e_typ, e_val, trcbak)):
raise e_typ, e_val, trcbak
# __exit__ code
with TstContx() as tc:
if hasattr(tc, 'init_exc'): raise tc.init_exc
# code in context
私が得ることができる限り近い、コンテキストマネージャは、最高のデザインの決定
問題は、 '__enter__'の中から' with'ボディをスキップすることはできません([pep 377](http://www.python.org/dev/peps/pep-0377/)を参照してください) – georg