Junior — Middle
What is the function of the __exit__ context manager in Python?
sobes.tech AI
Answer from AI
The __exit__ method in a Python context manager is called when exiting the with block. Its main task is to properly close resources, such as closing a file, releasing a database connection, or rolling back a transaction.
Additionally, __exit__ receives information about any exception that occurred within the with block. This allows handling the error, suppressing it, or passing it on. If the method returns True, the exception is considered handled and will not be propagated further.
Example of a simple context manager:
class MyContext:
def __enter__(self):
print('Entering context')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('Exiting context')
if exc_type:
print(f'Handled exception: {exc_type}')
# Return False to not suppress the exception
return False
with MyContext():
print('Inside block')
# raise ValueError('Error') # Uncomment to test exception handling