Phase 1 — Foundations · Lesson 4 · 20 XP
Python core III: exceptions, logging, generators, context managers
try/except/else/finally handles failure without crashing the program. Catch specific exceptions (except ZeroDivisionError), never a bare except — a bare except also swallows real bugs like typos in your own code. finally always runs, whether or not an exception happened, which is where cleanup belongs.
print() has no levels, no timestamps, and no way to turn it off in production without deleting code. The logging module gives you levels (DEBUG/INFO/WARNING/ERROR), timestamps, and configurable output — one line change routes every log call to a file or a log aggregator instead of stdout.
import logging
logger = logging.getLogger(__name__)
try:
result = 10 / 0
except ZeroDivisionError as e:
logger.error("division failed: %s", e)
finally:
print("cleanup always runs")A generator is a function with yield instead of return. Calling it doesn't run the body — it hands back an iterator that produces one value at a time, on demand. That means you can process a 10 GB log file line by line without ever holding the whole thing in memory.
def read_big_file(path):
with open(path) as f:
for line in f:
yield line.strip() # one line in memory at a timeA context manager (the with statement) guarantees cleanup runs even if the code inside raises — a file handle gets closed, a lock gets released, a connection gets returned to its pool. contextlib.contextmanager turns a generator function into one with a single decorator.
Exercise
Write a generator that yields lines from a file lazily. Write a context manager with @contextlib.contextmanager that times a block of code and logs the duration. Wrap a risky operation in try/except/finally using logging instead of print.
Check yourself
1. Why prefer a generator over building a full list when processing a huge file?
2. What does a context manager guarantee that a bare try/finally could also give you — so why use with instead?
Python core II: functions, dataclasses, pathlib, file I/O
Answer the check-yourself questions to unlock this