38
I see "with" statements used in Python. What are context managers and how do I create my own?
Loading...
Q&A · Answered
I see "with" statements used in Python. What are context managers and how do I create my own?
Accepted answer
# File handling (automatic close)
with open('file.txt', 'r') as f:
content = f.read()
# Multiple context managers
with open('input.txt', 'r') as fin, open('output.txt', 'w') as fout:
fout.write(fin.read())
from contextlib import contextmanager
@contextmanager
def timer():
import time
start = time.time()
yield
end = time.time()
print(f"Elapsed: {end - start:.2f}s")
# Usage
with timer():
# code to time
time.sleep(1)Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.