Parameterse
Besides the ubiquitous
self
parameter,
__exit__
also takes three additional parameters
The additional parameters are only releveant and distinct from
None
when
__exit__
is called because an
exception was raised after
__enter__
was called. In such a case, the three parameters have the following meaning:
The following example tries to demonstrate these parameters:
class Ex(Exception):
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
class RES:
def __enter__(self):
print('__enter__')
return self
def __exit__(self, exType, exValue, traceBack):
print(f'__exit__, exType: {str(exType)}, exValue: {str(exValue)}, traceBack: {str(traceBack)}')
try:
print('')
with RES():
print(' A')
print('')
with RES():
print(' B')
raise Ex('Something bad')
except Ex as ex:
print('')
print(f'Caught exception {str(ex)}')
When executed, the script prints
__enter__
A
__exit__, exType: None, exValue: None, traceBack: None
__enter__
B
__exit__, exType: <class '__main__.Ex'>, exValue: Something bad, traceBack: <traceback object at 0x000002C0AFC400C0>
Caught exception Something bad