Practical Context Manager Patterns
Apply context managers to files, locks, timers, and DB connections.
Practical Context Manager Patterns is a free Python Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Introduction
File Processing Pipeline
import io
src = io.StringIO('line1\nline2\nline3')
dst = io.StringIO()
with src, dst:
for line in src:
dst.write(line.upper())
print(dst.getvalue())Database Transaction
from contextlib import contextmanager
@contextmanager
def db_transaction(conn):
try:
yield conn
print('COMMIT')
except Exception as e:
print(f'ROLLBACK: {e}')
raise
finally:
print('CLOSE')
with db_transaction({'execute': lambda q: print(f'SQL: {q}')}) as db:
db['execute']('INSERT ...')Threading Lock
import threading
lock = threading.Lock()
shared = []
def add(x):
with lock:
shared.append(x)
add(1); add(2)
print(shared)Changing Directory
from contextlib import contextmanager
import os
@contextmanager
def chdir(path):
old = os.getcwd()
os.chdir(path)
try: yield
finally: os.chdir(old)
original = os.getcwd()
with chdir('/tmp'):
print('in tmp:', os.getcwd())
print('back:', os.getcwd())Temporary Files
import tempfile
with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=True) as f:
f.write('temp data')
print('temp file:', f.name)
print('deleted')Environment Variable Patch
from contextlib import contextmanager
import os
@contextmanager
def env(**kwargs):
old = {k: os.environ.get(k) for k in kwargs}
os.environ.update({k:str(v) for k,v in kwargs.items()})
try: yield
finally:
for k,v in old.items():
if v is None: os.environ.pop(k,None)
else: os.environ[k]=v
with env(DEBUG='1', LOG_LEVEL='DEBUG'):
print(os.environ['DEBUG'])Profiling Block
from contextlib import contextmanager
import cProfile
@contextmanager
def profile():
pr = cProfile.Profile()
pr.enable()
yield pr
pr.disable()
with profile() as pr:
sum(range(1000000))
print('profiled')Network Socket
import socket
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.settimeout(0.1)
print('socket ready')
except Exception as e:
print(f'socket: {e}')Capturing Warnings
import warnings
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
warnings.warn('test warning')
print(len(w), w[0].category.__name__)Combining Patterns
from contextlib import contextmanager
import time
@contextmanager
def timed_operation(name):
print(f'[{name}] start')
t0 = time.perf_counter()
try:
yield
print(f'[{name}] done in {time.perf_counter()-t0:.4f}s')
except Exception as e:
print(f'[{name}] failed: {e}')
raise
with timed_operation('loop'):
sum(range(100000))Quick Check
Recap
Keep Going
Frequently asked questions
Is the “Practical Context Manager Patterns” lesson free?
Yes — the full text of “Practical Context Manager Patterns” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Practical Context Manager Patterns”?
Apply context managers to files, locks, timers, and DB connections. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Practical Context Manager Patterns” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Python Academy lesson?
Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The with Statement in Depth
- __enter__ and __exit__ Protocol
- contextlib: @contextmanager
- Practical Context Manager Patterns