Context Managers (with Statement)
Context managers (with statement) ensure resources are properly cleaned up — files closed, connections released, locks freed. Always use them!
15 min•By Priygop Team•Updated 2026
Context Managers
Context Managers
# Basic context manager for files
# with open("file.txt") as f:
# data = f.read()
# f is automatically closed here!
# Without context manager (BAD!)
# f = open("file.txt")
# data = f.read()
# f.close() # Easy to forget!
# Multiple context managers
# with open("input.txt") as src, open("output.txt", "w") as dst:
# dst.write(src.read())
# Custom context manager with class
class Timer:
def __enter__(self):
import time
self.start = time.time()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
import time
self.elapsed = time.time() - self.start
print(f" Elapsed: {self.elapsed:.4f}s")
return False
# Usage
with Timer() as t:
total = sum(range(1_000_000))
print(f" Sum: {total}")
# Context manager with contextlib
from contextlib import contextmanager
@contextmanager
def managed_resource(name):
print(f" Opening {name}")
yield name
print(f" Closing {name}")
with managed_resource("database") as db:
print(f" Using {db}")Tip
Tip
Create your own context managers with __enter__/__exit__ or @contextmanager decorator for custom resource management.
Diagram
Loading diagram…
@decorator = syntactic sugar for fn = decorator(fn). Use functools.wraps to preserve metadata.
Common Mistake
Warning
Using open() without 'with' means you must remember to call .close() manually. If an exception occurs before close(), the file stays open.
Practice Task
Note
(1) Use 'with' to open and read a file. (2) Open two files simultaneously with 'with'. (3) Write a custom context manager.