added context managers

This commit is contained in:
aman committed 2026-04-09 22:14:57 +02:00
1 parent 35db4c9201
commit 5bf57d9fe6
2 files changed
+224

No files matched your search

+97
View File
@@ -0,0 +1,97 @@
# Create two context managers:
# Timer class — measures how long the code inside with takes:
# pythonwith Timer("my task") as t:
# import time
# time.sleep(1)
# # my task took 1.00 seconds
# FileBackup class — before writing to a file, creates a backup copy. If an error occurs during writing, restores the backup:
# python# Creates backup, writes safely
# with FileBackup("data.txt") as f:
# f.write("new content")
# # Success — backup is deleted
# # Creates backup, error occurs
# with FileBackup("data.txt") as f:
# f.write("partial content")
# raise ValueError("oops")
# # Error — original file restored from backup
# Start with Timer — it's simpler. Give it a shot!
import os
import time
class Timer:
def __init__(self, task_name: str):
self.task_name=task_name
def __enter__(self):
self.start = time.time()
print(f"running {self.task_name}...")
return self.start
def __exit__(self, exc_type, exc, tb):
import time
time_took = time.time() - self.start
if exc_type:
print(f"an {exc_type} occured as follows - {exc}, here is the complete traceback - {tb}")
print(f"task {self.task_name} executed successfully in {time_took} seconds")
# test
with Timer("my task") as t:
import time
time.sleep(1) # should i put the import in the class for bettwer logic, so that i can say it took this many seconds? or is there a better way to do this?
class FileBackup:
def __init__(self, name: str):
self.name=name
self.bk_name=f"{self.name}_bk"
def __enter__(self):
print("opening the file for writing...")
#open(self.name, "w")
if os.path.exists(self.name):
with open(self.name, "r+") as f:
og_content = f.read()
with open(self.bk_name, "w+") as b:
b.write(og_content)
# back to main use
self.file = open(self.name, "w+")
return self.file
def __exit__(self, exc_type, exc, tb):
# closing first
self.file.close()
if exc_type:
print(f"a {exc_type} occured as follows -- {exc}, here is the complete traceback - {tb}")
print("restoring from the backup")
with open(self.bk_name, "r+") as b:
og_content = b.read()
with open(self.name, "w+") as f:
f.write(og_content)
else:
print("successfully completed the writing")
if os.path.exists(self.bk_name):
os.remove(self.bk_name)
print("removed the backup post successful writing")
return True
# ---
# test
with FileBackup("data.txt") as f:
f.write("new content")
# Success — backup is deleted
with FileBackup("data.txt") as f:
f.write("partial content")
raise ValueError("oops")
# Error — original file restored from backup
+127
View File
@@ -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)