Czy możliwe jest wywołanie metody __exit__()
, nawet jeśli istnieje wyjątek w wersji __enter__()
?Wyłapywanie wyjątków w menedżerze kontekstów __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__
>>>
Edit
To jest tak blisko, jak mogę dostać ...
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
W tylnej wzroku, kierownik kontekst może nie być najlepsza decyzja konstrukcja
Problem polega na tym, że nie można pominąć 'with' ciała z' __enter__' (patrz [pep 377] (http://www.python.org/dev/peps/pep-0377/)) – georg