Catching exception in context manager __enter__()
问题 Is it possible to ensure the __exit__() method is called even if there is an exception in __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 This is as close as I could get...