Junior — Middle
What methods should a class implement to be used in a with statement for automatic resource management?
sobes.tech AI
Answer from AI
To use a class in a with statement in Python, it must implement the context manager methods:
__enter__(self): called when entering thewithblock. Usually, resource initialization occurs here, and the method returns an object that will be accessible inside the block.__exit__(self, exc_type, exc_val, exc_tb): called when exiting thewithblock, even if an exception occurs inside the block. Resources are typically released here or cleanup is performed.
Example:
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
with FileManager('test.txt', 'w') as f:
f.write('Hello, world!')