Python › File I/O & Context Managers
How do you write and use a custom context manager by implementing __enter__ and __exit__?
IntermediateAnswer
Define a class with __enter__ (running setup logic and returning the value bound by 'as') and __exit__ (running cleanup logic, receiving any exception info that occurred inside the 'with' block) — the 'with' statement automatically calls __enter__ on entry and __exit__ on exit, regardless of how the block ends.
class Timer:
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, exc_type, exc_value, tb):
elapsed = time.time() - self.start
print(f"Took {elapsed:.2f}s")
with Timer():
do_expensive_work()Real-world example Building a custom resource manager (like a database connection or a performance timer) with guaranteed setup/teardown behavior.