A context manager is a Python object typically used to allocate resources before running the code and automatically release or clean them up afterward..
They are most commonly used with the
withstatement to handle files, database locks safely, ensuring cleanup happens even if an error occurs.You can write a context manager either by creating a class with
enterandexitmethods, or by using the@contextmanagerdecorator from the built-in contextlib module.
import time
class Timer:
def __enter__(self):
print("Timer started...")
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.end = time.time()
print(f"Elapsed time: {self.end - self.start:.4f} seconds")
# Return False or None to let any exceptions propagate normally
return False
# Using the context manager
with Timer():
time.sleep(1)
print("Doing some work inside the block...")
# Generator-Based Context Manager: You can also write context managers cleanly using the contextlib module
from contextlib import contextmanager
import time
@contextmanager
def timer():
print("Timer started...")
start = time.time()
try:
yield
finally:
end = time.time()
print(f"Elapsed time: {end - start:.4f} seconds")
with timer():
time.sleep(1)
print("Doing some work inside the block...")