क्या यह सुनिश्चित करना संभव है कि __exit__()
विधि को __enter__()
में अपवाद होने पर भी यह सुनिश्चित किया जा सके?संदर्भ प्रबंधक में अपवाद को पकड़ना __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__' के भीतर से 'शरीर' को छोड़ना संभव नहीं है (देखें [पेप 377] (http://www.python.org/dev/peps/pep-0377/)) – georg