97 lines
2.9 KiB
Python
97 lines
2.9 KiB
Python
# 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 |