Python Context Manager
Is a protocol for managing resources, such as files, is used with the with keyword
The 2 methods we have to be aware of are:
__enter__(): Called when entering the with block
__exit__(): Called when exiting the with block (Exceptions also call this method)
Example with filehandler:
class FileHandler:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
self.file = None
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()
# Using the context manager
with FileHandler('example.txt', 'w') as f:
f.write('Hello World')
# File is automatically closed after the block
We can also use the @contextmanager decorator from contextlib (External dependency)
Example:
from contextlib import contextmanager
@contextmanager
def temporary_file(filename, mode):
f = open(filename, mode)
try:
yield f
finally:
f.close()
# Using the context manager
with temporary_file('example.txt', 'w') as f:
f.write('Hello World')