added context managers
This commit is contained in:
1 parent
35db4c9201
commit
5bf57d9fe6
2 files changed
+224
No files matched your search
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
Python Context Managers Practice
|
||||
==================================
|
||||
Concepts covered:
|
||||
1. __enter__ and __exit__ dunder methods
|
||||
2. The 'with' statement — guaranteed setup and cleanup
|
||||
3. Error handling inside context managers
|
||||
4. exc_type, exc_val, exc_tb parameters in __exit__
|
||||
5. return True/False to suppress or propagate exceptions
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 1. TIMER — Measures execution time of code inside 'with' block
|
||||
# Demonstrates: __enter__ for setup, __exit__ for cleanup/reporting
|
||||
# =============================================================================
|
||||
|
||||
class Timer:
|
||||
"""Context manager that measures how long a block of code takes."""
|
||||
|
||||
def __init__(self, task_name: str):
|
||||
self.task_name = task_name
|
||||
|
||||
def __enter__(self):
|
||||
self.start = time.time()
|
||||
print(f"Starting '{self.task_name}'...")
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
elapsed = time.time() - self.start
|
||||
if exc_type:
|
||||
print(f" Error during '{self.task_name}': {exc}")
|
||||
print(f" '{self.task_name}' took {elapsed:.2f} seconds")
|
||||
return False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 2. FILE BACKUP — Safe file writing with automatic backup and restore
|
||||
# Demonstrates: setup (backup), cleanup (restore or delete backup),
|
||||
# error handling, and guaranteed resource cleanup
|
||||
# =============================================================================
|
||||
|
||||
class FileBackup:
|
||||
"""Context manager that backs up a file before writing.
|
||||
On success: backup is deleted.
|
||||
On error: original file is restored from backup.
|
||||
"""
|
||||
|
||||
def __init__(self, filename: str):
|
||||
self.filename = filename
|
||||
self.backup_name = f"{filename}.bk"
|
||||
|
||||
def __enter__(self):
|
||||
# Save existing content as backup
|
||||
if os.path.exists(self.filename):
|
||||
with open(self.filename, "r") as f:
|
||||
content = f.read()
|
||||
with open(self.backup_name, "w") as bk:
|
||||
bk.write(content)
|
||||
|
||||
# Open file for writing and return it
|
||||
self.file = open(self.filename, "w")
|
||||
return self.file
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
# Always close the file first
|
||||
self.file.close()
|
||||
|
||||
if exc_type:
|
||||
# Error occurred — restore from backup
|
||||
print(f" Error: {exc}")
|
||||
if os.path.exists(self.backup_name):
|
||||
with open(self.backup_name, "r") as bk:
|
||||
content = bk.read()
|
||||
with open(self.filename, "w") as f:
|
||||
f.write(content)
|
||||
print(f" Restored '{self.filename}' from backup")
|
||||
return True # suppress the exception
|
||||
else:
|
||||
# Success — remove backup
|
||||
if os.path.exists(self.backup_name):
|
||||
os.remove(self.backup_name)
|
||||
print(f" Successfully wrote to '{self.filename}', backup removed")
|
||||
return False
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# 3. TESTS
|
||||
# =============================================================================
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
# --- Timer ---
|
||||
print("=== Timer ===")
|
||||
with Timer("sleep test") as t:
|
||||
time.sleep(1)
|
||||
|
||||
print()
|
||||
|
||||
# --- FileBackup: successful write ---
|
||||
print("=== FileBackup: Success ===")
|
||||
with FileBackup("data.txt") as f:
|
||||
f.write("new content")
|
||||
|
||||
# Verify content was written
|
||||
with open("data.txt", "r") as f:
|
||||
print(f" File contains: '{f.read()}'")
|
||||
|
||||
print()
|
||||
|
||||
# --- FileBackup: error during write ---
|
||||
print("=== FileBackup: Error Recovery ===")
|
||||
with FileBackup("data.txt") as f:
|
||||
f.write("this should be rolled back")
|
||||
raise ValueError("something broke!")
|
||||
|
||||
# Verify original content was restored
|
||||
with open("data.txt", "r") as f:
|
||||
print(f" File contains: '{f.read()}'")
|
||||
|
||||
# --- Cleanup test files ---
|
||||
for filename in ("data.txt", "data.txt.bk"):
|
||||
if os.path.exists(filename):
|
||||
os.remove(filename)
|
||||
Reference in new issue
Block a user