140. Creating and Handling Custom Context Managers
1. Basic Context Manager with contextlib.contextmanager
contextlib.contextmanagerfrom contextlib import contextmanager
@contextmanager
def my_open_file(file_name, mode):
print(f"Opening file: {file_name}")
file = open(file_name, mode)
try:
yield file # Provides control back to the with statement
finally:
file.close()
print(f"Closing file: {file_name}")
# Using the custom context manager
with my_open_file('test.txt', 'w') as file:
file.write("Hello, world!")Output:
Explanation:
2. Context Manager for Database Connections
Output:
Explanation:
3. Custom Context Manager for Timer
Output:
Explanation:
4. Context Manager with Custom Exception Handling
Output:
Explanation:
5. Context Manager for Resource Locking
Output:
Explanation:
6. Context Manager with Multiple Resources
Output:
Explanation:
7. Context Manager for Logging
Output:
Explanation:
8. Context Manager for File Backup
Output:
9. Context Manager with Configuration Changes
Output:
10. Context Manager for Network Resource
Output:
Explanation:
Conclusion:
Last updated