The function is called , regardless of whether the body causes errors or not. Your function must have additional parameters (exception type), (exception object), and (generated trace). __exit__withexc_typeexc_valuetraceback
, with Error, : None. , .
, , , , , .
, , , :
class A(object):
def __enter__(self):
self.file = open('some_file.txt')
return self.file
def __exit__(self, exc_type, exc_value, traceback):
print(('exit', exc_type, exc_value, traceback))
self.file.close()
return False
- :
with A():
raise Exception
, __exit__ :
('exit', <class 'Exception'>, Exception(), <traceback object at 0x7fc512c924c8>)
, . , , , SQL .
__exit__ ( , Python None). , __exit__ True, : with. with. , - .
class SilenceExceptions(object):
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
return True
:
with SilenceExceptions():
raise Error
, "" __exit__.