Context managers handle resource setup and teardown, ensuring cleanup even on errors. Beyond with open()
, create custom ones using classes or contextlib
.
Using a Class:
class ManagedFile:
def __init__(self, filename):
self.filename = filename
def __enter__(self):
self.file = open(self.filename, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
# Usage
with ManagedFile('hello.txt') as f:
f.write('Hello, context manager! ๐')
Using contextlib
:
from contextlib import contextmanager
@contextmanager
def managed_file(filename):
try:
f = open(filename, 'w')
yield f
finally:
f.close()
# Usage
with managed_file('hello2.txt') as f:
f.write('Even cleaner! ๐งผ')
This is the Pythonic way for resource management.