Mastering Python's contextlib Module 🧰
Mastering Python's contextlib Module 🧰
The contextlib module provides helpful utilities to efficiently manage resources with Python's context managers, making your code cleaner and safer.
1. @contextmanager: Simple Context Managers
from contextlib import contextmanager
@contextmanager
def open_file(name, mode):
f = open(name, mode)
try:
yield f
finally:
f.close()
with open_file('test.txt', 'w') as f:
f.write('Hello, world!')
2. closing: Manage Objects that Need Closing
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('http://example.com')) as page:
for line in page:
print(line)
3. suppress: Ignore Specific Exceptions
from contextlib import suppress
import os
with suppress(FileNotFoundError):
os.remove('somefile.tmp')
4. redirect_stdout: Redirect Output
from contextlib import redirect_stdout
with open('output.txt', 'w') as f:
with redirect_stdout(f):
print('This will go into the file')
Summary
- Use
@contextmanagerto easily write custom context managers. closinglets you manage resources that require explicit closure.suppresshelps ignore specific exceptions gracefully.redirect_stdoutenables easy redirection of output to files or other streams.
Comments
Post a Comment