01A.8 Errors, Exceptions, Debugging and Logging
So far this module has taught you Python that works. This lesson teaches you what to do when it doesn't — which is most of the time, for everyone, including the best engineers alive. You'll learn to read a traceback (the report card Python hands you when something goes wrong) line by line, to catch the right exceptions at the right boundary instead of letting programs die mysteriously, to use context managers so resources clean up even when things fail, to debug with print, breakpoint() and pdb, and to replace print debugging with proper logging that survives production. By the end you'll have a robust loader for the ticket-triage data that reports every bad row instead of crashing on the first one — the same pattern that later carries you through LLM API calls, where "something went wrong" is a normal Tuesday.
What you'll learn
- The three kinds of errors — syntax, runtime and logic — and why each needs a different fix
- The built-in exception hierarchy: which exception means what, and how to read any traceback line by line, including chained exceptions
try/except/else/finally, EAFP vs LBYL,raise,raise ... from ..., custom exception classes,ExceptionGroup/except*,warnings,assert,sys.exitandKeyboardInterrupt- Context managers:
with,__enter__/__exit__,@contextlib.contextmanager,ExitStack, and a timer you write yourself - Error-handling design: when to catch, when to propagate, error messages that help, validation at boundaries, and why "catch everything" is a bug factory
- Debugging tools: disciplined
printdebugging,breakpoint()andpdb, thetracebackmodule,-X dev,-W error,faulthandler, bisecting and minimal reproductions - The
loggingmodule done properly: loggers, levels, handlers, formatters, lazy formatting, file and rotating logs — and what never to log - A testing preview:
assert,doctest, and tiny test functions (pytest gets its own lesson in Module 01B) - A worked example: robust CSV loading that collects per-row errors instead of crashing
What you don't need
- Any third-party package, an API key, or a running service. Everything here is the standard library.
- Testing frameworks —
pytestis Module 01B.8's topic; this lesson only previews the habits. - Formal exception theory. If you can read a function signature, you can read everything here.
Setup
You need Python 3.11 or newer and a text editor — nothing else. The tracebacks and outputs in this lesson were produced with Python 3.14.6; on 3.11–3.15 the caret positions, suggestion wording and occasional messages can differ slightly (3.13 adds colour to tracebacks on a terminal; everything else here is stable). If you don't have Python yet, see 01A.1 for uv/python.org install routes, or Module 00 lesson 00.1 for the machine setup.
What you must be able to do after this lesson#
- Tell syntax, runtime and logic errors apart
- Read a traceback including chained exceptions
- Handle errors with try, except, else and finally
- Raise and define custom exceptions
- Use a with block and write a simple context manager
- Debug with print, breakpoint and pdb
- Set up logging with levels and a file handler
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
"The script died with a KeyError on row 4,000 of the export." |
Part 2: Reading a traceback and Part 9: the robust loader |
"Wrap the API call in a try/except and retry." |
Part 3: handling errors and Part 5: when to catch |
| "Don't swallow the exception — log it and re-raise." | 5.6 and Part 7: logging |
"The model returned invalid JSON — handle the JSONDecodeError." |
5.8: errors in LLM apps |
| "Rate limits and timeouts are normal; retry with backoff." | 5.7: the retry preview → lesson 03.8 |
| "Add a correlation ID and log every call as JSON." | Part 7 → lesson 03.10 and lesson 11A.1 |
| "Never log the prompt — it contains user PII." | 7.7: what not to log → lesson 12.4 |
| "Reproduce the bug with the smallest possible input." | 6.6: minimal reproductions → lesson 00.9 |
Part 1: The three kinds of errors#
Every bug you've ever hit is one of three things, and the fix is different for each:
| Kind | When it appears | Example | How you find it |
|---|---|---|---|
| Syntax error | Before the program runs at all — Python can't parse the file | Missing colon, unclosed bracket, bad indentation | The interpreter refuses to start and points at the line |
| Runtime error (an exception) | While the program runs, when an operation can't complete | 1 / 0, missing dict key, None + 1 |
A traceback is printed and the program exits |
| Logic error | The program runs "fine" and produces wrong answers | Off-by-one in a loop, price * qty - discount instead of price * qty * (1 - discount) |
Only tests, careful reading, or a debugger catch it — nothing "fails" |
1.1 Syntax errors#
Python won't run a file it can't parse. In the REPL you see the error immediately:
>>> def f(:
File "<stdin>", line 1
def f(:
^
SyntaxError: invalid syntaxIn a script, the whole file fails before line 1 executes — so a syntax error on line 400 means nothing ran, including your careful setup code. Since Python 3.10 the caret (^) points at the exact character; since 3.11 tracebacks also mark the offending expression with ^^^^ carets (more on that in 2.4). Python 3.14 even suggests corrections for common slips, like whille → while or elif after else (What's New in 3.14).
1.2 Runtime errors: exceptions#
When an operation can't complete — dividing by zero, looking up a key that isn't there, calling a method on None — Python raises an exception: it stops what it was doing and hands the problem up the call stack. If nothing catches it, the program ends with a traceback: a report of where it happened, what was being executed, and what kind of error it was.
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
1 / 0
~~^~~
ZeroDivisionError: division by zeroThe ~~^~~ carets are the 3.11+ feature pointing at the exact sub-expression (/ here) that failed — see 2.4.
1.3 Logic errors: the silent killers#
A logic error produces a plausible-looking wrong result with no traceback at all. The pdb_target.py bug you'll debug in 6.2 is exactly this: price * qty - discount computes 199.9 where the correct price * qty * (1 - discount) gives 180. Nothing crashes; the number is just wrong.
Part 2: The exception hierarchy and reading tracebacks#
2.1 The exception hierarchy#
Every exception is an object — an instance of a class — and all exception classes descend from BaseException. The part of the tree you'll meet daily:
flowchart TB
BE["BaseException<br/>(catch this only for truly fatal exits)"]
E["Exception<br/>(almost everything you should catch)"]
BE --> E
BE --> KE["KeyboardInterrupt<br/>(Ctrl+C)"]
BE --> SE["SystemExit<br/>(sys.exit())"]
BE --> GNE["GeneratorExit<br/>(closing a generator early)"]
E --> AEE["ArithmeticError"]
AEE --> ZDE["ZeroDivisionError"]
E --> LE["LookupError"]
LE --> KE2["KeyError"]
LE --> IE["IndexError"]
E --> ATE["AttributeError"]
E --> TE["TypeError"]
E --> VE["ValueError"]
E --> NE["NameError"]
E --> RE["RuntimeError"]
E --> OE["OSError"]
OE --> FNFE["FileNotFoundError"]
OE --> PE["PermissionError"]
OE --> TE2["TimeoutError"]
E --> IOE["ImportError → ModuleNotFoundError"]
E --> SEE["StopIteration"]
E --> GE["ExceptionGroup (3.11+)"]The single most important rule: catch Exception, never BaseException — KeyboardInterrupt and SystemExit inherit directly from BaseException precisely so that a broad except Exception doesn't swallow Ctrl+C or sys.exit().
| Exception | Usually means |
|---|---|
SyntaxError / IndentationError |
The file can't be parsed — fix the code, not the data |
NameError |
A name isn't defined where you used it (typo, missing import, wrong scope) |
TypeError |
Wrong type for the operation: "a" + 1, calling a non-callable, wrong argument count |
ValueError |
Right type, wrong value: int("abc"), a date that doesn't exist |
KeyError |
Missing dict key — often a missing .get() or a renamed field |
IndexError |
List/tuple index out of range — classic off-by-one |
AttributeError |
Object has no such attribute — None.foo, typo, or wrong object type |
FileNotFoundError |
Path doesn't exist (subclass of OSError, which covers permissions, disk-full, etc.) |
ZeroDivisionError |
Division by zero (subclass of ArithmeticError) |
StopIteration |
next() on an exhausted iterator — normally handled for you by for |
ImportError / ModuleNotFoundError |
Missing package, typo in the module name, or the wrong environment/venv |
UnicodeDecodeError / UnicodeEncodeError |
Text/bytes conversion failed — usually a wrong encoding= (01A.2) |
TimeoutError |
An operation timed out (an OSError subclass; socket.timeout became an alias of it in 3.10) |
RuntimeError |
A generic "something went wrong" — often raised deliberately by libraries and your own code |
RecursionError |
Too-deep recursion hit the limit |
MemoryError |
Out of memory — rarely catchable usefully |
KeyboardInterrupt |
The user pressed Ctrl+C — let it propagate or clean up and re-raise |
SystemExit |
sys.exit() was called — carries the exit code |
GeneratorExit |
Raised inside a generator when it's closed early (.close(), or garbage collection) — why bare except: is dangerous |
2.2 Anatomy of a traceback, line by line#
Here's the script and the real traceback it produces — tb_callstack.py, a nested call chain (paths shortened):
# tb_callstack.py — nested calls so the traceback shows a real call stack
def parse_ticket(raw):
fields = raw.split("|")
return {"id": fields[0], "priority": int(fields[2])}
def load_one(line):
return parse_ticket(line.strip())
def main():
tickets = [load_one(line) for line in ["T-1042|login broken|high"]]
print(tickets)
main()python3 tb_callstack.pyTraceback (most recent call last):
File "tb_callstack.py", line 13, in <module>
main()
~~~~^^
File "tb_callstack.py", line 10, in main
tickets = [load_one(line) for line in ["T-1042|login broken|high"]]
~~~~~~~~^^^^^^
File "tb_callstack.py", line 7, in load_one
return parse_ticket(line.strip())
File "tb_callstack.py", line 4, in parse_ticket
return {"id": fields[0], "priority": int(fields[2])}
~~~^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: 'high'Read it bottom-up for the cause, top-down for the journey:
Traceback (most recent call last):— the header. "Most recent call last" means the bottom frame is where the error happened; the frames above are the callers that led there.- Each
File "...", line N, in funcnameblock is one stack frame — a function that was still on the call stack when the error hit.<module>means top-level script code. The~~~~^^line under the code is the 3.11+ fine-grained location: the carets underline the exact expression that raised (here, theint(fields[2])call inside the dict display). - The last line is the exception:
ValueError: invalid literal for int() with base 10: 'high'. The class name tells you the kind; the message tells you the details. - The journey matters:
main→ list comprehension →load_one→parse_ticket. The bug is inparse_ticket(it triedint()on the string"high"— the ticket format puts priority in a different field), but the fix might belong inload_one(validate before parsing) — the traceback shows you both the crash site and the path that got there.
2.3 Chained exceptions: "During handling..."#
When an exception is raised while another is being handled, Python chains them so you see both. Two flavours:
- Implicit chaining — you raise a new exception inside an
exceptblock withoutfrom. The output saysDuring handling of the above exception, another exception occurred:. - Explicit chaining —
raise NewError(...) from original. The output saysThe above exception was the direct cause of the following exception:and sets__cause__, which tools likelogger.exceptionand debuggers display deliberately.
Real output, implicit chain first. The script, tb_implicit2.py:
# tb_implicit2.py — implicit chaining: raise inside except WITHOUT `from`
def parse_age(text):
return int(text)
def load_ticket(line):
try:
age = parse_age(line.split(",")[1])
except ValueError as e:
raise RuntimeError(f"cannot parse ticket row: {line!r}")
return age
load_ticket("T-1,notanumber")python3 tb_implicit2.pyTraceback (most recent call last):
File "tb_implicit2.py", line 7, in load_ticket
age = parse_age(line.split(",")[1])
File "tb_implicit2.py", line 3, in parse_age
return int(text)
ValueError: invalid literal for int() with base 10: 'notanumber'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "tb_implicit2.py", line 12, in <module>
load_ticket("T-1,notanumber")
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
File "tb_implicit2.py", line 9, in load_ticket
raise RuntimeError(f"cannot parse ticket row: {line!r}")
RuntimeError: cannot parse ticket row: 'T-1,notanumber'Then explicit chaining — tb_explicit.py:
# tb_explicit.py — explicit chaining with `raise ... from ...`
class ConfigError(Exception):
"""The application cannot start without a valid config."""
def load_config(path):
try:
with open(path, encoding="utf-8") as f:
return f.read()
except FileNotFoundError as e:
raise ConfigError(f"cannot start without config {path!r}") from e
load_config("missing-config.txt")python3 tb_explicit.pyTraceback (most recent call last):
File "tb_explicit.py", line 7, in load_config
with open(path, encoding="utf-8") as f:
~~~~^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'missing-config.txt'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "tb_explicit.py", line 12, in <module>
load_config("missing-config.txt")
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^
File "tb_explicit.py", line 10, in load_config
raise ConfigError(f"cannot start without config {path!r}") from e
ConfigError: cannot start without config 'missing-config.txt'The rule of thumb: chain explicitly when the new exception replaces the old one as the story ("config missing" is the real problem; "file not found" is the mechanism), and let it chain implicitly when you're just letting a different error escape. raise ... from None suppresses the context entirely — use it only when the original error would actively mislead.
2.4 Python 3.11 and later: traceback improvements#
- 3.10: better
SyntaxErrorpointers, andNameError/AttributeError"did you mean" suggestions —NameError: name 'schwarschild_black_hole' is not defined. Did you mean: schwarzschild_black_hole?(What's New 3.10). - 3.11 (What's New, PEP 657): carets under the exact failing expression in every frame;
ExceptionGroup/except*;BaseException.add_note(). - 3.12/3.13: the suggestions grew teeth —
Did you forget to import 'sys'?forNameError,self.attribute hints,ImportErrorname guesses (What's New 3.12) — and 3.13 colours tracebacks by default on terminals: disable withNO_COLOR=1,PYTHON_COLORS=0orTERM=dumb(FORCE_COLOR, if set at all, forces colour on — useful on CI, useless for disabling) (What's New 3.13). - 3.14 (What's New): keyword-typo suggestions (
whille→while), specific messages forelif-after-else, clearer unpacking counts, and the specific unhashable-key messagecannot use 'list' as a dict key (unhashable type: 'list').
Part 3: Handling errors with try/except#
3.1 The anatomy of try#
# handling.py
def parse_port(text):
"""Parse a port number; raise ValueError on bad input."""
port = int(text)
if not 1 <= port <= 65535:
raise ValueError(f"port {port} out of range 1-65535")
return port
def connect(port_text):
# try: only the risky part. else: runs only if NO exception.
# finally: runs no matter what (cleanup).
try:
port = parse_port(port_text)
except (ValueError, TypeError) as e: # tuple of exception types
print(f"bad port {port_text!r}: {e}")
return None
else:
print(f"connecting to port {port}")
return port
finally:
print(" (connection attempt finished)")
print(connect("8080"))
print(connect("abc"))
print(connect("99999"))connecting to port 8080
(connection attempt finished)
8080
bad port 'abc': invalid literal for int() with base 10: 'abc'
(connection attempt finished)
None
bad port '99999': port 99999 out of range 1-65535
(connection attempt finished)
NoneThe four clauses, precisely:
try:— only the code that can realistically fail goes here. Keep it small.except SomeError as e:— runs when a matching exception propagates.eis the exception object;str(e)is its message. Severalexceptclauses are tried in order; a tuple(ValueError, TypeError)catches either.else:— runs only whentrycompleted without an exception. This is where "the operation succeeded, now do the follow-up" code belongs, so that follow-up errors aren't accidentally caught by your ownexcept.finally:— runs always: success, handled exception, unhandled exception, evenreturninsidetry. This is the cleanup guarantee — close files, release locks, log "attempt finished".
3.2 Catch specific exceptions#
except matches by class and its subclasses. FileNotFoundError is an OSError, so:
try:
data = load_config(path)
except FileNotFoundError:
... # only missing files
except OSError:
... # permissions, disk full, etc. — but NOT FileNotFoundError (already caught)
except Exception:
... # everything else — use sparingly, always re-raise or logOrder matters: specific first, general last. The same rule the LLM lessons apply to provider exception trees (03.8, 3.7).
3.3 EAFP vs LBYL#
Two philosophies for dealing with possible failure:
- EAFP — Easier to Ask Forgiveness than Permission: just do the operation inside
try, catch the failure. Pythonic, and usually faster because the check and the act are one step. - LBYL — Look Before You Leap: check conditions first (
if key in d,if path.exists()), then act. Necessary when the "check" itself is the logic, or when failure isn't an exception (e.g. an API returning an error value).
# eafp.py
tickets = {"T-1": {"status": "open"}, "T-2": {"status": "closed"}}
def lbyl(ticket_id):
# Look Before You Leap: check first, then act
if ticket_id in tickets and "status" in tickets[ticket_id]:
return tickets[ticket_id]["status"]
return "unknown"
def eafp(ticket_id):
# Easier to Ask Forgiveness than Permission: just try it
try:
return tickets[ticket_id]["status"]
except KeyError:
return "unknown"
for tid in ["T-1", "T-9"]:
print(f"{tid}: lbyl={lbyl(tid)!r:10} eafp={eafp(tid)!r}")T-1: lbyl='open' eafp='open'
T-9: lbyl='unknown' eafp='unknown'Both return the same answers — run eafp.py to confirm — but EAFP wins when the condition is complex ("status" in tickets[t] still doesn't guarantee no race between check and use), and LBYL wins when "absent" is normal data, not an error (a .get() with a default is the LBYL spirit in one call). The deeper trap: checking is not atomic — between if path.exists() and open(path) the file can disappear. EAFP is the only race-free option.
3.4 The sins: bare except, swallowed errors, lost tracebacks#
try:
process(row)
except: # SIN 1: catches KeyboardInterrupt, SystemExit, EVERYTHING
pass # SIN 2: swallows the error — silent data loss- Bare
except:catchesBaseException— including Ctrl+C. Always name the exception(s) you mean. except Exception: passis the classic silent killer: the program continues with missing data and nobody knows. If you catch, you must do something: log, collect the error, re-raise, or return a defined fallback.- Losing the traceback:
except ValueError: raise RuntimeError("bad")withoutfromstill chains implicitly (you saw it in 2.3), butraise ... from Noneor catching-and-returning a bare string destroys the "where". Preferraise NewError(...) from eand attach context withe.add_note()(3.11+). finallycan silently override areturn: areturninsidefinallydiscards thetryblock's result and any in-flight exception. Almost never what you want.
try:
return compute()
finally:
cleanup()
# NO return here — it would swallow compute()'s result AND any exception3.5 raise, re-raise and sys.exc_info()#
# rereraise.py — a bare `raise` re-raises the exception you're already handling
def parse_age(text):
return int(text)
def load_ticket(line):
try:
return parse_age(line.split(",")[1])
except ValueError:
print(" (log context or clean up here — then:)")
raise # bare `raise`: the SAME ValueError keeps propagating
try:
load_ticket("T-1,notanumber")
except ValueError as e:
print(f"outer caught {type(e).__name__}: {e}") (log context or clean up here — then:)
outer caught ValueError: invalid literal for int() with base 10: 'notanumber'A bare raise inside except preserves the original exception and its traceback — it's how you add a log line or cleanup step without changing behaviour. Outside an except block, bare raise is a RuntimeError: No active exception to re-raise.
Two sys helpers expose "the exception currently being handled". sys.exc_info() returns the (type, value, traceback) triple — mostly for logging and framework code that wants all three parts. On 3.11+ prefer sys.exception(), which returns just the exception object, or None when no exception is being handled:
import sys
try:
int("abc")
except ValueError:
print(f"exc_info type: {sys.exc_info()[0].__name__}")
print(f"sys.exception(): {sys.exception()!r}")
print(f"outside except: {sys.exception()}")exc_info type: ValueError
sys.exception(): ValueError("invalid literal for int() with base 10: 'abc'")
outside except: None3.6 Custom exceptions and hierarchies#
Libraries and applications define their own exception classes so callers can catch precisely. The convention: one AppError root, themed subclasses, and the message says what happened and why:
# custom_exc.py — a small exception hierarchy for the triage tool
class AppError(Exception):
"""Base class for every error this application raises on purpose."""
class TicketError(AppError):
"""Something is wrong with a ticket row."""
class TicketParseError(TicketError):
"""A row could not be parsed into a ticket."""
def __init__(self, row, field, reason):
super().__init__(f"row {row!r}: bad {field} ({reason})")
self.row, self.field, self.reason = row, field, reason
def parse_priority(raw, row):
try:
p = int(raw)
except ValueError as e:
raise TicketParseError(row, "priority", f"expected int, got {raw!r}") from e
if p not in (1, 2, 3):
raise TicketParseError(row, "priority", f"must be 1-3, got {p}")
return p
try:
parse_priority("urgent", "T-9")
except TicketParseError as e:
print(f"caught {type(e).__name__}: {e}")
print(f" details: row={e.row} field={e.field} reason={e.reason}")
print(f" is AppError? {isinstance(e, AppError)} is TicketError? {isinstance(e, TicketError)}")caught TicketParseError: row 'T-9': bad priority (expected int, got 'urgent')
details: row=T-9 field=priority reason=expected int, got 'urgent'
is AppError? True is TicketError? TrueDesign rules that scale: derive from a domain base (AppError), not directly from Exception, so except AppError catches all your deliberate failures while except Exception still catches the unexpected. Put structured detail on attributes (e.row, e.field) — callers can react to data, not just parse the message. This is exactly the shape the provider SDKs use (APIStatusError, RateLimitError, APIConnectionError in the OpenAI/Anthropic SDKs — 03.8, 3.1).
3.7 ExceptionGroup and except* (3.11+)#
When several independent operations each fail, ExceptionGroup bundles the exceptions so one try can report all of them, and except* matches subgroups by type:
# eg_demo.py — ExceptionGroup bundles failures; except* matches them by type
def risky(n):
if n == 2:
raise ValueError(f"ticket {n} has a bad field")
if n == 4:
raise KeyError(f"ticket {n} is missing")
return n * 10
def batch(ns):
errors, out = [], []
for n in ns:
try:
out.append(risky(n))
except Exception as e:
errors.append(e)
if errors:
raise ExceptionGroup("batch had failures", errors)
return out
try:
batch([1, 2, 3, 4, 5])
except* ValueError as eg:
print(f"except* ValueError caught {len(eg.exceptions)}: {eg.exceptions[0]}")
except* KeyError as eg:
print(f"except* KeyError caught {len(eg.exceptions)}: {eg.exceptions[0]!r}")except* ValueError caught 1: ticket 2 has a bad field
except* KeyError caught 1: KeyError('ticket 4 is missing')Run it and both except* clauses fire — one per exception type inside the group. The takeaway is awareness for now: asyncio.TaskGroup raises ExceptionGroup when child tasks fail, so except* is how you handle "some of the calls failed" in async code (Module 01B.3 owns async — 03-async-await-and-the-event-loop; the 01B overview has the lesson map). Plain except Exception on an ExceptionGroup catches the whole group — fine when you just want "did anything fail?".
3.8 The other error tools#
| Tool | What it is | When to use |
|---|---|---|
warnings.warn(msg, Category) |
A non-fatal "heads up" printed once per location by default | Deprecations, dodgy-but-working input; DeprecationWarning is hidden outside __main__ by default |
assert cond, msg |
Raises AssertionError if cond is false; removed entirely by python -O |
Internal invariants ("this can't happen"), never input validation |
sys.exit(code) / sys.exit("msg") |
Raises SystemExit; string prints to stderr and exits 1, int sets the code |
CLI programs signalling success/failure to the shell |
KeyboardInterrupt |
Raised on Ctrl+C | Catch only to clean up, then raise — never swallow |
contextlib.suppress(E) |
with suppress(E): ignores matching exceptions |
"Try this; it's fine if it fails" — makes the ignore visible in code |
e.add_note("...") (3.11+) |
Attaches a note shown in the traceback | Add context while propagating: except KeyError as e: e.add_note("checked tickets.csv"); raise |
# warn_demo.py — warnings are not exceptions; filters can escalate them
import warnings
def load_legacy_format(text):
warnings.warn("pipe-delimited tickets are deprecated; use CSV", DeprecationWarning, stacklevel=2)
return text.split("|")
print(load_legacy_format("T-1|open|high"))
print("done")stacklevel=2 makes the warning point at your caller's line — warn_demo.py:8, the print(...) — instead of inside load_legacy_format; that's why the default-run warning cites line 8, not line 5.
=== default run of warn_demo.py ===
warn_demo.py:8: DeprecationWarning: pipe-delimited tickets are deprecated; use CSV
print(load_legacy_format("T-1|open|high"))
['T-1', 'open', 'high']
done
=== python3 -W error::DeprecationWarning warn_demo.py ===
Traceback (most recent call last):
File "warn_demo.py", line 8, in <module>
print(load_legacy_format("T-1|open|high"))
~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "warn_demo.py", line 5, in load_legacy_format
warnings.warn("pipe-delimited tickets are deprecated; use CSV", DeprecationWarning, stacklevel=2)
~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
DeprecationWarning: pipe-delimited tickets are deprecated; use CSV
(exit=1)-W error::DeprecationWarning turns the warning into an exception — the same mechanism pytest uses to surface warnings, and a trick you can use to audit a codebase for deprecated calls. Filters: -W error, -W ignore::DeprecationWarning, -W always, or warnings.filterwarnings(...) in code; python -W help lists the syntax.
Exit codes, verified — the two tiny scripts and their runs:
# exit_demo.py — sys.exit() with a code; the shell reads $?
import sys
def main(argv):
if "--dry-run" in argv:
print("dry run: nothing written")
return 0
print("work done")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))# exit_fail.py — a failing CLI exits non-zero
import sys
sys.exit("cannot read tickets.csv: file not found")$ python3 exit_demo.py --dry-run
dry run: nothing written
exit=0
$ python3 exit_fail.py
cannot read tickets.csv: file not found
exit=1
$ python3 -c "raise SystemExit(3)"
exit=3The contract: 0 = success, anything else = failure, and the number can carry meaning (grep's 1 vs 2, your own CLI's codes). sys.exit("msg") is the polite way to fail with a message; uncaught exceptions exit 1 too but with a traceback — choose deliberately.
e.add_note() deserves its own demo, because it is the cleanest way to add "which row, which file" context without wrapping the exception in a new type (so callers' except ValueError still matches). Notes are stored in e.__notes__ and printed under the final traceback line:
# note_demo.py — add_note(): context added while the exception keeps propagating
def parse(row):
return int(row["qty"])
row = {"id": "T-7", "qty": "three"}
try:
parse(row)
except ValueError as e:
e.add_note(f"while parsing ticket {row['id']}")
e.add_note("source: tickets.csv line 8")
print(e.__notes__)
raiseOutput (stdout line first, then the traceback on stderr; script paths shortened):
['while parsing ticket T-7', 'source: tickets.csv line 8']
Traceback (most recent call last):
File "note_demo.py", line 7, in <module>
parse(row)
~~~~~^^^^^
File "note_demo.py", line 3, in parse
return int(row["qty"])
ValueError: invalid literal for int() with base 10: 'three'
while parsing ticket T-7
source: tickets.csv line 8The bare raise keeps the original traceback intact (compare 3.5), and the notes appear after the message, in the order they were added. Prefer a note over wrapping when the type is still the right story; prefer raise NewError(...) from e when a different type is.
Part 4: Context managers#
4.1 with and the protocol behind it#
You've used with open(...) since early lessons; 01A.9 owns file handling. The mechanism is more general: any object with __enter__ and __exit__ methods is a context manager, and with cm as x: is sugar for "call __enter__, bind its return to x, run the block, then call __exit__ — even if the block raised". __exit__ receives (exc_type, exc, traceback) — all None on clean exit — and returning True suppresses the exception.
# cm_class.py — the class form of a context manager: __enter__ / __exit__
class Timer:
def __enter__(self):
print("enter: start")
return "handle" # what `as x` binds
def __exit__(self, exc_type, exc, tb):
# runs on the way out, BOTH on success and on exception
print(f"exit: exc_type={exc_type}")
return False # False = don't suppress; True = swallow
print("--- normal exit ---")
with Timer() as t:
print(f"inside, got {t!r}")
print("--- exceptional exit ---")
try:
with Timer():
raise ValueError("boom")
except ValueError as e:
print(f"caught outside: {e}")--- normal exit ---
enter: start
inside, got 'handle'
exit: exc_type=None
--- exceptional exit ---
enter: start
exit: exc_type=<class 'ValueError'>
caught outside: boomThat's the whole protocol — setup in __enter__, guaranteed teardown in __exit__. Files, locks, database connections, timers, temporary directories: all context managers because "must be released even on failure" is the universal need.
You can manage several resources in a single with — each __exit__ still runs, in reverse order of entry:
with open(src, encoding="utf-8") as fin, open(dst, "w", encoding="utf-8") as fout:
fout.write(fin.read()) # both files close even if write() raises(3.10+ also allows a parenthesised multi-line form when the line gets long; nested with blocks do the same thing with more indentation.)
4.2 @contextlib.contextmanager: write one in five lines#
Subclassing for every little resource is heavy. @contextmanager turns a generator function into a context manager: code before yield is __enter__, code after is __exit__:
from contextlib import contextmanager
import time
@contextmanager
def timer(label):
start = time.perf_counter()
try:
yield lambda: time.perf_counter() - start # `as x` gets the elapsed() fn
finally:
print(f"{label}: {time.perf_counter() - start:.4f}s")
def slow_sum(n):
return sum(i * i for i in range(n))
with timer("sum") as elapsed:
result = slow_sum(2_000_000)
print(f"result={result} inner={elapsed():.4f}s")sum: 0.0718s
result=2666664666667000000 inner=0.0721sNote the try/finally inside the generator: if the with body raises, the exception is thrown back into the generator at the yield, so the finally still prints. If you don't catch it there, it propagates — exactly like __exit__ returning False.
Other contextlib tools you'll meet: suppress(exc) (3.8), closing(obj) (calls .close() on objects that have it but are not context managers themselves), nullcontext() (a do-nothing placeholder, handy for "use a lock only if one was passed in"), redirect_stdout/redirect_stderr (testing), chdir, and ExitStack — a stack of context managers you enter dynamically and that unwinds all of them in reverse order:
# exitstack.py — ExitStack: enter several resources, all closed in reverse order
from contextlib import ExitStack, suppress
class Resource:
def __init__(self, name): self.name = name
def __enter__(self):
print(f" open {self.name}")
return self
def __exit__(self, *exc):
print(f" close {self.name} (exc={exc[0].__name__ if exc[0] else None})")
return False
def work():
with ExitStack() as stack:
stack.enter_context(Resource("db"))
stack.enter_context(Resource("cache"))
stack.enter_context(suppress(ValueError)) # swallow ValueError only
raise ValueError("boom") # suppressed -> no propagation
work()
print("all resources closed cleanly") open db
open cache
close cache (exc=None)
close db (exc=None)
all resources closed cleanlySubtle and worth knowing: exits run LIFO (cache before db), and once suppress handles the ValueError, the earlier exits see exc=None — suppression happens at the point in the stack where it's registered. ExitStack matters when the number of resources isn't known until runtime — e.g. opening one connection per tenant.
lock_cm.py — the lock-as-context-manager demo
# lock_cm.py — `with lock:` is a context manager too
import threading
counter = {"n": 0}
lock = threading.Lock()
def worker():
for _ in range(100_000):
with lock: # acquire ... release guaranteed, even on error
counter["n"] += 1
threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads: t.start()
for t in threads: t.join()
print(f"counter={counter['n']} (4 x 100_000 = 400_000)")counter=400000 (4 x 100_000 = 400_000)Part 5: Error-handling design#
Tools are easy; judgement is the job. These are the decisions that separate code that survives production from code that survives the demo.
5.1 When to catch, when to propagate#
| Situation | Do |
|---|---|
| You can do something useful with the failure (retry, fallback, skip the row, show a message) | Catch it, narrowly |
| You can't — the caller might handle it differently, or the error is genuinely unexpected | Let it propagate |
You're at the top level (CLI main, request handler) |
Catch broadly once, log with traceback, exit/report cleanly |
| In a library | Almost never catch — raise your own typed errors and let the application decide |
The library rule is the one people break: a library that catches Exception and returns None has made the failure invisible to every caller. Libraries raise; applications handle. The provider SDKs follow this — openai raises RateLimitError/APIConnectionError and your code decides (03.8).
5.2 Error messages that help#
A good exception message answers three questions: what failed, where/which input, and what to do about it. Compare:
raise ValueError("bad input") # useless
raise ValueError(f"priority {raw!r} for row {row} is not 1-3") # useful
raise TicketParseError(row, "priority", f"expected int, got {raw!r}") from e # best: structured + chainedRules: include the offending value ({raw!r} — !r so strings show quotes and escapes), name the field, and when raising from another error keep from e so the chain survives. When you catch at a boundary, add context with e.add_note() instead of wrapping when the original type matters.
5.3 Validation at boundaries#
Validate once, at the edge where untrusted data enters: CSV rows, API responses, user input, config files. Inside the boundary, trust your types — re-checking every dict access is over-defensive noise. The triage loader (Part 9) validates each row once in parse_row, then hands clean Ticket objects inward. Same idea as Pydantic in 01B.6: validate at the boundary, work with typed objects inside.
5.4 Returning errors vs raising#
| Return an error value | Raise an exception |
|---|---|
The "error" is a normal, expected outcome (lookup miss → None, parse → try_parse tuple) |
The operation cannot produce its result |
The caller must check anyway (.get(), is not None) |
The caller shouldn't have to remember to check |
| Cheap, local, frequent | Rare, exceptional, needs stack context |
Python's own idiom: dict.get() returns None for a missing key (return style), while d[key] raises KeyError (raise style) — both exist because both patterns are legitimate. Choose per call site; don't mix them for the same failure.
5.5 Cleanup guarantees and resource leaks#
Every acquired resource — file, socket, lock, connection, temp dir — needs a release path that runs on every exit, including exceptions. That's precisely what with (Part 4) buys you. The leak pattern to recognise:
f = open(path) # if anything below raises, f stays open
try:
data = f.read()
finally:
f.close() # works, but verbose — `with open(path) as f:` does bothtry/finally is the manual version; with is the idiom. In long-running services, leaked connections/locks are the classic slow-motion outage — this is why "cleanup in finally/__exit__" is a design rule, not a style preference.
5.6 Logging then re-raising#
The boundary pattern you'll use constantly: log what you saw (with context your caller lacks), then raise so the failure still propagates. Part 7 gives logging its own treatment — for now, log.exception(msg) inside except means "log the message plus the full traceback":
# boundary.py — at the edge: log what you saw, then let the error propagate
import logging
logging.basicConfig(level=logging.WARNING,
format="%(levelname)s %(name)s: %(message)s")
log = logging.getLogger("orders")
def line_total(item):
return float(item["price"]) * int(item["qty"])
def checkout(items):
total = 0.0
for item in items:
try:
total += line_total(item)
except (KeyError, ValueError) as e:
# you hold context the caller lacks: which item, its raw form
log.exception("checkout failed on item %r", item)
raise # log-then-re-raise: the failure still propagates
return total
try:
checkout([{"price": "10.5", "qty": "2"},
{"price": "oops", "qty": "1"}])
except ValueError as e:
print(f"checkout aborted: {e}")ERROR orders: checkout failed on item {'price': 'oops', 'qty': '1'}
Traceback (most recent call last):
File "boundary.py", line 15, in checkout
total += line_total(item)
~~~~~~~~~~^^^^^^
File "boundary.py", line 9, in line_total
return float(item["price"]) * int(item["qty"])
~~~~~^^^^^^^^^^^^^^^
ValueError: could not convert string to float: 'oops'
checkout aborted: could not convert string to float: 'oops'The sibling pattern — collect and continue — is the one load_tickets uses in Part 9: one bad row shouldn't kill 4,000 good ones, so the per-item except logs the skip, appends the error and moves on. Choose between them by asking "is this failure fatal to the batch, or just to this item?".
Two more boundary patterns: fail fast — at startup/config time, an error should kill the process loudly (sys.exit with a clear message) rather than limp along misconfigured; and the top-level catch — one broad except Exception at the entry point that logs the traceback and exits non-zero, so unexpected bugs still produce a report instead of a silent hang. For exceptions that escape every try, Python calls sys.excepthook (and threading.excepthook for a crashing thread, which otherwise dies with only a stderr message while the rest of the program carries on); assigning your own function there is how frameworks route "uncaught" errors into the log. You rarely need it in a script — a main() with one top-level try is simpler — but now you know where the "Traceback (most recent call last)" printout comes from.
5.7 Retries: a preview#
Retry is the most common "handling" — and the most misused. The rules that matter even before 01B.9/03.8 go deep: only retry transient failures (timeouts, 429, 5xx — never a 400 or a validation error), always with a cap and backoff, and only for idempotent operations (a retried POST that already succeeded server-side can double-charge). Never write while True: try: ... except: pass — that's an infinite retry storm. The full treatment: 01B.9 retries and 03.8.
5.8 Errors in LLM apps: a preview#
LLM calls add failure modes a CSV parser never sees — all covered later, previewed here so the vocabulary lands:
- Rate limits (429) and overload (529) — transient; retry with backoff, honour
Retry-After(03.8, Part 4, 9). - Timeouts — the model may still finish server-side; decide whether retrying duplicates work (03.8, Part 6).
- Invalid JSON / schema violations — the model answered but not in the shape you need; that's a validation error, not a transport one — validate-and-retry with the errors fed back (03.4, Part 7, and its 6.4 three non-answers: refusal, truncation and safety blocks are not the same as bad JSON).
- Errors inside HTTP 200 — providers can return a successful status carrying a failure body; the outcome check runs before parsing (03.8, Part 10).
- Partial failures in batches — one bad row/call shouldn't kill the batch; collect per-item errors exactly like
load_ticketsdoes (Part 9).
Part 6: Debugging#
6.1 Print debugging, done well#
Before reaching for a debugger, print is legitimate — if you print usefully. The two habits that matter:
# print_debug.py — print debugging done well: repr and f"{x=}"
tickets = [{"id": "T-1", "tags": []}, {"id": "T-2", "tags": ["vip"]}]
for t in tickets:
print(t) # looks fine until you know tags should be non-empty
target = tickets[0]
print(f"{target=}") # shows the expression AND its repr — no guessing
print(f"{target['tags']=}")
print(f"{len(target['tags'])=}")
name = "T-1\nINJECT"
print(f"plain: {name}") # the newline makes output lie about structure
print(f"repr : {name!r}") # shows \n explicitly{'id': 'T-1', 'tags': []}
{'id': 'T-2', 'tags': ['vip']}
target={'id': 'T-1', 'tags': []}
target['tags']=[]
len(target['tags'])=0
plain: T-1
INJECT
repr : 'T-1\nINJECT'Rules: f"{x=}" prints x=<repr> — the name and the value in one keystroke; !r/repr() when the value is a string, so quotes, newlines and escapes are visible; print at decision points (inputs, branches taken, intermediate values), not everywhere; and delete or downgrade the prints before committing — they're scaffolding, not logging (Part 7 is the permanent version).
6.2 breakpoint() and pdb#
breakpoint() drops you into the standard debugger pdb at that line — no imports, works in scripts and tests. Remove the call (or set PYTHONBREAKPOINT=0) when done; editors honour it too.
# pdb_target.py — a small buggy function to debug
def total_price(ticket):
price = ticket["price"]
qty = ticket.get("qty", 1)
discount = ticket.get("discount", 0)
return price * qty - discount # BUG: should be price * qty * (1 - discount)
def main():
t = {"id": "T-1", "price": 100, "qty": 2, "discount": 0.1}
print(f"total={total_price(t)}") # expected 180, got 199.9
main()python3 -m pdb pdb_target.py # or: PYTHONBREAKPOINT=0 to disable breakpoint()A real session against a planted bug — total_price computes price * qty - discount (199.9) instead of price * qty * (1 - discount) (180). python3 -m pdb pdb_target.py first stops at the top of the file (line 2); type break total_price then continue to jump straight into the function (or step through main()). Transcript trimmed to the interesting part — paths shortened:
> pdb_target.py(3)total_price()
-> price = ticket["price"]
(Pdb) next
> pdb_target.py(4)total_price()
-> qty = ticket.get("qty", 1)
(Pdb) next
> pdb_target.py(5)total_price()
-> discount = ticket.get("discount", 0)
(Pdb) next
> pdb_target.py(6)total_price()
-> return price * qty - discount
(Pdb) p discount
0.1
(Pdb) p price * qty
200
(Pdb) continue
total=199.9The commands that carry 90% of sessions: n/next (step over), s/step (step into), c/continue, l/list (show code), p expr/pp expr (print), w/where (stack), u/d (up/down a frame), b line/b func (breakpoint), q (quit). python -m pdb -c continue script.py runs non-interactively — useful for "post-mortem" debugging of a crash. Full command list: pdb docs. Python 3.14 adds python -m pdb -p PID, which attaches the debugger to an already running process (PEP 768, What's New in 3.14) — handy for a stuck worker you can't restart; 01B.10 covers post-mortem debugging and attaching in full.
6.3 The VS Code debugger#
The same breakpoint() works in VS Code: the editor stops there, and its debug sidebar gives you what pdb makes you type — a variables pane, a watch list, a call-stack view, hover-to-inspect, and a debug console that evaluates expressions in the stopped frame. Set a breakpoint by clicking the gutter; press F5. For pytest, debug a single test via the test explorer's bug icon. You don't need pdb's keystrokes day-to-day, but knowing pdb pays off on servers and in CI where there's no editor (01B.10 covers launch.json and debugging async/FastAPI).
6.4 The traceback module#
When you catch an exception but want its traceback as data — log it, store it, attach it to a report — the traceback module formats it without re-raising:
# tb_module.py — the traceback module: catch, format, log, continue
import traceback
def parse(row):
return int(row.split(",")[1])
rows = ["T-1,3", "T-2,unknown", "T-3,7"]
for row in rows:
try:
print(f"{row}: age={parse(row)}")
except ValueError:
print(f"{row}: FAILED — full traceback follows")
traceback.print_exc() # prints to stderr, like an uncaught one
print("--- end traceback ---")Output (run with python3 -u — unbuffered, so stdout and stderr interleave in true order):
T-1,3: age=3
T-2,unknown: FAILED — full traceback follows
Traceback (most recent call last):
File "tb_module.py", line 10, in <module>
print(f"{row}: age={parse(row)}")
~~~~~^^^^^
File "tb_module.py", line 5, in parse
return int(row.split(",")[1])
ValueError: invalid literal for int() with base 10: 'unknown'
--- end traceback ---
T-3,7: age=7traceback.format_exc() returns the same text as a string (for logs), traceback.format_exception(e) formats a specific exception, and traceback.print_exception(e) prints it. logger.exception(...) (7.3) does this for you inside except.
6.5 Interpreter flags that expose bugs#
| Flag / tool | What it does |
|---|---|
python3 -X dev |
Dev mode: enables PYTHONDEVMODE — turns on extra warnings (e.g. ResourceWarning for unclosed files), faulthandler, and asyncio debug |
python3 -W error |
Escalates all warnings to exceptions — warnings become failures |
python3 -W error::DeprecationWarning |
Same, for one category only (3.8) |
faulthandler |
Dumps the Python stack on segfault/abort — or on demand with dump_traceback() |
python3 -v |
Verbose import tracing — "which module is slow/where does this name come from" |
python3 -X importtime |
Per-import timing table — the profiling cousin of -v |
python3 -X dev dev_demo.py on a file that's never closed produces the following (the whole script is five lines — shown so you can reproduce it):
# dev_demo.py — run with: python3 -X dev dev_demo.py
import warnings
f = open("dev_demo_tmp.txt", "w") # never closed -> ResourceWarning under -X dev
f.write("hi")
warnings.warn("custom warning shown in dev mode", UserWarning)dev_demo.py:5: UserWarning: custom warning shown in dev mode
warnings.warn("custom warning shown in dev mode", UserWarning)
<sys>:0: ResourceWarning: unclosed file <_io.TextIOWrapper name='dev_demo_tmp.txt' mode='w' encoding='UTF-8'>The ResourceWarning is the point: dev mode shows the leak that normal runs hide. faulthandler.dump_traceback() printed the stack on demand — the script (faulthandler_demo.py) is:
# faulthandler_demo.py — dump the stack on demand (or automatically on a crash)
import faulthandler, sys
def level3():
faulthandler.dump_traceback() # what a segfault handler would print
def level2(): level3()
def level1(): level2()
print("about to dump")
level1()
print("done")Trimmed here (about to dump prints first and done last — the excerpt keeps only the dump itself):
Current thread 0x00000001fce0d300 (most recent call first):
File "faulthandler_demo.py", line 5 in level3
File "faulthandler_demo.py", line 7 in level2
File "faulthandler_demo.py", line 8 in level1
File "faulthandler_demo.py", line 11 in <module>(The thread id differs every run; the stack is what matters.) It's what you'd see after a hard crash in C extensions or os._exit — the last resort when there's no traceback.
6.6 Rubber-ducking, bisecting and minimal reproductions#
The non-tool half of debugging, all covered properly in lesson 00.9:
- Rubber-duck it: explain the bug out loud, line by line, as if to someone else — the act of narrating finds the wrong assumption faster than silent staring.
- Bisect: if it worked yesterday,
git bisect(00.3, git fundamentals / 00.4, GitHub) finds the exact commit; if it fails on input N, binary-search the input size to find the threshold. - Minimal reproduction: strip the failing case to the smallest input that still fails — 3 lines beat 300, and it's what you paste into a bug report or a test (00.9, 4.3).
- Change one thing: the scientific loop — hypothesise, change one variable, observe. Three changes at once and you learn nothing.
Part 7: Logging#
7.1 Why not print#
print writes to stdout, unconditionally, unstructured, unfilterable. In a script that's fine; in a service it means: no levels (debug noise in prod), no file rotation (disk fills), no timestamps/levels/which-module (can't answer "when did this start?"), and it pollutes stdout that might be a protocol channel (JSON-RPC, HTTP). Logging gives you levels, destinations, formats and filters — and it's in the standard library.
7.2 The moving parts#
flowchart LR
subgraph loggers ["Loggers (named, hierarchical)"]
L2["getLogger('triage.load')<br/>(child)"]
L1["getLogger('triage')<br/>(parent)"]
root["root logger"]
end
subgraph handlers ["Handlers (where records go)"]
H1["StreamHandler → stderr"]
H2["FileHandler → app.log"]
H3["RotatingFileHandler → app.log.1, .2"]
end
subgraph formatters ["Formatters (how records look)"]
F1["'%(levelname)s %(name)s: %(message)s'"]
end
L2 -- "propagates up" --> L1
L1 -- "propagates up" --> root
root --> H1
root --> H2
H1 -.-> F1
H2 -.-> F1- Logger — a named channel (
logging.getLogger("triage.load")). Loggers form a hierarchy on.; a record propagates up to every ancestor's handlers unlesspropagate = False— a child logger never "owns" a handler, it borrows its ancestors'. - Handler — decides where a record goes:
StreamHandler(stderr by default),FileHandler,RotatingFileHandler,TimedRotatingFileHandler,SMTPHandler, and more inlogging.handlers. - Formatter — decides how it looks:
%(asctime)s %(levelname)s %(name)s %(message)s. - Level —
DEBUG < INFO < WARNING < ERROR < CRITICAL; a record is emitted only if it's ≥ the logger's effective level.
Two stdlib neighbours worth knowing: logging.captureWarnings(True) routes the warnings module's output through the logging pipeline (on the py.warnings logger) — one switch connecting 3.8 to this part. And logging.NullHandler is the documented pattern for libraries: attach one to your logger and records are silently discarded unless the application configures handlers — which is exactly why libraries never call basicConfig (7.3).
7.3 Loggers, levels and getLogger(__name__)#
# log_basic.py — the logging module: levels, getLogger, lazy formatting
import logging
# Configure ONCE, at the top of the program (the "root" logger's handler)
logging.basicConfig(
level=logging.INFO,
format="%(levelname)s %(name)s: %(message)s",
)
# A script uses a literal name; inside a real module this is getLogger(__name__),
# which yields dotted paths like "triage.load" — see the rule below.
log = logging.getLogger("triage")
log.debug("this is invisible: level is INFO")
log.info("loaded 3 tickets")
try:
{}["missing"]
except KeyError:
log.exception("failed to read ticket field") # ERROR + traceback, automatically
# lazy formatting: the f-string version would build the string even when DEBUG is off
count = 42
log.debug("count is %s", count) # %s args are only formatted if emitted
log.debug(f"count is {count}") # f-string ALWAYS formats (wasted work)
print("--- done ---")INFO triage: loaded 3 tickets
ERROR triage: failed to read ticket field
Traceback (most recent call last):
File "log_basic.py", line 18, in <module>
{}["missing"]
~~^^^^^^^^^^^
KeyError: 'missing'
--- done ---The rules that matter:
getLogger(__name__)in libraries/modules — the logger's name is the module path, sotriage.loadrecords can be filtered or levelled independently, and libraries never callbasicConfig(that's the application's job — a library that configures root logging hijacks the host app). The companion pattern islogging.NullHandler: a library attaches one to its logger so its records are silently discarded unless the application configures handlers — "I have somewhere records could go" without deciding where.- A record must clear two level gates — the logger's effective level and each handler's own level (
handler.setLevel(...), defaultNOTSET= pass everything).log.setLevel(DEBUG)alone doesn't help if the handler sits atWARNING; converselybasicConfig(level=DEBUG)with aWARNINGhandler still dropsDEBUG. This is the classic "why didn't my DEBUG line print" bug. - Lazy
%sargs, never f-strings in log calls —log.debug("x=%s", expensive())costs one method call when DEBUG is off; the f-string builds the string anyway. Same forlog.info("%d rows", len(rows)). log.exception(msg)insideexcept=log.error(msg, exc_info=True)— ERROR level plus the full traceback. It's the "log then re-raise" partner (5.6).basicConfigonce, at program start (orlogging.config.dictConfigfor real apps — 01B.10 owns that). Calling it twice does nothing unlessforce=True.
7.4 File and rotating handlers#
# log_file.py — handlers decide WHERE records go; formatters decide HOW they look
import logging
from pathlib import Path
# FileHandler opens the file immediately and does NOT create parent directories —
# without this line a fresh directory dies with FileNotFoundError. (01A.9 owns paths properly.)
Path("logs").mkdir(exist_ok=True)
log = logging.getLogger("triage")
log.setLevel(logging.DEBUG)
log.propagate = False # don't also send to root's handlers
fmt = logging.Formatter("%(levelname)s %(name)s %(message)s")
console = logging.StreamHandler() # default: stderr
console.setFormatter(fmt)
file_h = logging.FileHandler("logs/triage.log", encoding="utf-8")
file_h.setFormatter(fmt)
log.addHandler(console)
log.addHandler(file_h)
for i in range(3):
log.info("processed batch %d", i)
log.warning("skipped 2 malformed rows")
print("wrote logs/triage.log")Both destinations get every record (console and file); logs/triage.log ends up identical to the console stream. For production-sized logs, RotatingFileHandler rolls over by size — the whole script (log_rotate.py, which exercise 10 has you modify):
# log_rotate.py — RotatingFileHandler: when the file passes maxBytes it rolls over
import logging
from logging.handlers import RotatingFileHandler
from pathlib import Path
Path("logs").mkdir(exist_ok=True) # same rule as log_file.py
handler = RotatingFileHandler(
"logs/app.log", maxBytes=200, backupCount=2,
encoding="utf-8",
)
handler.setFormatter(logging.Formatter("%(message)s"))
log = logging.getLogger("demo")
log.setLevel(logging.INFO)
log.propagate = False
log.addHandler(handler)
for i in range(20):
log.info("ticket batch %02d processed ok", i)
print("done — inspect logs/app.log and logs/app.log.1, .2")Verified: 20 info lines at ~29 bytes each (ticket batch NN processed ok\n) with maxBytes=200, backupCount=2 produced app.log holding the last two lines, app.log.1 the previous six, app.log.2 the six before that — oldest beyond .2 deleted (six records fit under 200 bytes; the seventh triggers the roll). (TimedRotatingFileHandler rotates by when — daily/weekly — the usual choice for services.) Always pass encoding="utf-8" to file handlers, same rule as open().
7.5 A note on print vs log in scripts#
For a CLI tool, print for user-facing output (results, tables) and log for diagnostics (progress, warnings, errors) is the clean split — diagnostics belong on stderr so they don't corrupt piped output. logging defaults to stderr for exactly this reason.
7.6 Structured logging: a preview#
Plain-text logs answer "what happened"; structured logs (one JSON object per line, or key=value pairs) answer "how many", "which feature", "what's the p95" — you can grep and aggregate them. 03.10 builds JSON-lines logging for LLM calls field by field, and 01B.10 owns dictConfig, structlog and redaction filters; 11A.1 turns the same records into traces. The habit to start now: log events with fields, not sentences — log.warning("skipped row", extra={"row": n, "reason": e.reason}) is greppable; log.warning(f"skipped row {n}: {e.reason}") is not (and it's an f-string — lazy-formatting violation anyway). Two catches: the default format string does not print extra fields — they become attributes on the record, so you must reference them (%(row)s) or use a JSON formatter — and extra keys may not collide with built-in record attributes such as name, message or args (KeyError: "Attempt to overwrite 'name' in LogRecord"), so name them row, reason, ticket_id and so on.
7.7 What not to log: secrets and PII#
Part 8: A testing preview#
Deep-dive
Two free tools before pytest arrives in 01B.8:
assertin aif __name__ == "__main__"block or acheck()function — the zero-dependency smoke test.assert median([1,2,3]) == 2fails loudly withAssertionErrorand shows the expression.doctest— examples in docstrings are tests:
# stats.py — doctests: examples in docstrings that are also tests
def median(values):
"""Return the median of a non-empty list of numbers.
>>> median([3, 1, 2])
2
>>> median([1, 2, 3, 4])
2.5
>>> median([])
Traceback (most recent call last):
...
ValueError: median of empty list
"""
if not values:
raise ValueError("median of empty list")
xs = sorted(values)
n = len(xs)
mid = n // 2
return xs[mid] if n % 2 else (xs[mid - 1] + xs[mid]) / 2python3 -m doctest stats.py -v reported 3 tests in stats.median ... 3 passed. A tiny test_*.py with plain functions and asserts covers the same ground — run by a hand-rolled loop like this one (tiny_test.py, importing the stats.py from above):
# tiny_test.py — assert-based tests you can run with plain python (pytest comes in 01B.8)
from stats import median
def test_median_odd():
assert median([3, 1, 2]) == 2
def test_median_even():
assert median([1, 2, 3, 4]) == 2.5
def test_median_empty_raises():
try:
median([])
except ValueError:
pass
else:
raise AssertionError("median([]) should raise ValueError")
if __name__ == "__main__":
for name, fn in sorted((k, v) for k, v in globals().items() if k.startswith("test_")):
fn()
print(f"PASS {name}")PASS test_median_empty_raises
PASS test_median_even
PASS test_median_odd(python -m unittest won't run these — it discovers unittest.TestCase classes only; plain test_* functions are pytest's discovery model, which is one reason pytest won. It arrives in 01B.8.) The habit that matters now: every function you write gets at least one example you can run, because "it looks right" is how logic errors ship.
Part 9: Putting it together: robust ticket loading#
Deep-dive
The module's running example lands here: loading ticket rows where some rows are bad and the rest must survive. This is the canonical "validate at the boundary, collect errors, log skips" pattern — the same shape as batch LLM jobs later.
# triage_load.py — robust CSV loading: per-row errors, a custom exception, logging
import csv
import io
import logging
from dataclasses import dataclass
log = logging.getLogger("triage.load")
class AppError(Exception):
"""Base class for every error this application raises on purpose."""
class TicketParseError(AppError):
"""One CSV row could not be turned into a ticket."""
def __init__(self, row_number: int, raw, reason: str):
super().__init__(f"row {row_number}: {reason} (raw={raw!r})")
self.row_number = row_number
self.raw = raw # the whole row dict for missing-field errors, the offending cell for value errors
self.reason = reason
@dataclass(frozen=True)
class Ticket:
ticket_id: str
subject: str
priority: int # 1 = low, 2 = normal, 3 = high
status: str
REQUIRED = ("ticket_id", "subject", "priority", "status")
def _cell(raw, column):
# DictReader gives None for missing trailing fields; normalise to ""
return (raw.get(column) or "").strip()
def parse_row(row_number: int, raw: dict) -> Ticket:
"""Turn one CSV row (a dict of strings) into a Ticket, or raise."""
missing = [c for c in REQUIRED if not _cell(raw, c)]
if missing:
raise TicketParseError(row_number, raw, f"missing {', '.join(missing)}")
try:
priority = int(_cell(raw, "priority"))
except ValueError as e:
raise TicketParseError(row_number, _cell(raw, "priority"),
"priority is not a number") from e
if priority not in (1, 2, 3):
raise TicketParseError(row_number, _cell(raw, "priority"),
"priority must be 1, 2 or 3")
return Ticket(_cell(raw, "ticket_id"), _cell(raw, "subject"),
priority, _cell(raw, "status"))
def try_parse(row_number: int, raw: dict):
"""Return (ticket, None) or (None, TicketParseError) — never raises."""
try:
return parse_row(row_number, raw), None
except TicketParseError as e:
return None, e
def load_tickets(text: str):
"""Parse CSV text into (tickets, errors). Bad rows are collected, not fatal."""
tickets, errors = [], []
reader = csv.DictReader(io.StringIO(text))
for row_number, raw in enumerate(reader, start=2): # line 1 is the header
ticket, error = try_parse(row_number, raw)
if error is not None:
errors.append(error)
log.warning("skipping row %d: %s", row_number, error.reason)
else:
tickets.append(ticket)
return tickets, errors
CSV_TEXT = """ticket_id,subject,priority,status
T-1001,Printer on floor 3 offline,3,open
T-1002,VPN drops every morning,2,in_progress
,Missing id row,1,open
T-1004,Badge reader broken,urgent,open
T-1005,Request new monitor,2,open
T-1006,Keyboard keys sticking,9,closed
T-1007,Login loop after update,2,open
T-1008,Only two fields
"""
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format="%(levelname)s %(name)s: %(message)s")
tickets, errors = load_tickets(CSV_TEXT)
print(f"loaded {len(tickets)} tickets, {len(errors)} bad rows")
for t in tickets:
print(f" ok {t.ticket_id} p{t.priority} {t.status}: {t.subject}")
for e in errors:
print(f" ERR {e}")Run python3 -u triage_load.py (unbuffered so log records and prints interleave in true order). Output:
WARNING triage.load: skipping row 4: missing ticket_id
WARNING triage.load: skipping row 5: priority is not a number
WARNING triage.load: skipping row 7: priority must be 1, 2 or 3
WARNING triage.load: skipping row 9: missing priority, status
loaded 4 tickets, 4 bad rows
ok T-1001 p3 open: Printer on floor 3 offline
ok T-1002 p2 in_progress: VPN drops every morning
ok T-1005 p2 open: Request new monitor
ok T-1007 p2 open: Login loop after update
ERR row 4: missing ticket_id (raw={'ticket_id': '', 'subject': 'Missing id row', 'priority': '1', 'status': 'open'})
ERR row 5: priority is not a number (raw='urgent')
ERR row 7: priority must be 1, 2 or 3 (raw='9')
ERR row 9: missing priority, status (raw={'ticket_id': 'T-1008', 'subject': 'Only two fields', 'priority': None, 'status': None})Every design decision from this lesson is in this one file: a typed error (TicketParseError hanging off the AppError base from 3.6, with .row_number/.reason attributes — except AppError catches every deliberate failure in this tool), chaining (from e keeps the ValueError context), EAFP at the boundary (try_parse never raises), collection not propagation (one bad row doesn't kill 4,000 good ones), logging the skips with lazy %s args, and io.StringIO adapting the text to the file-like stream csv.DictReader iterates — the same reader pattern consumes real files in 01A.9, which owns the csv details and file I/O. The caller gets (tickets, errors) — data it can report on, not an exception it can't recover from.
Common mistakes gallery#
Six error-handling sins behind most "it worked on my machine" and "the data silently went missing" incidents — each with real output:
# mistakes_gallery.py — the six sins, each in isolation
import logging
import sys
import traceback
# 1. bare except catches BaseException — even SystemExit and Ctrl+C
try:
sys.exit(3)
except:
print("1. bare except caught SystemExit(3) — KeyboardInterrupt dies here too")
# 2. swallowed exception: the bad row vanishes with no trace
loaded = []
for raw in ["4", "oops", "7"]:
try:
loaded.append(int(raw))
except ValueError:
pass
print("2. swallowed -> loaded:", loaded, "(no error, no log, no trace)")
# 3. losing the traceback: three ways to re-raise, three different stories
def inner():
return int("not-a-number")
def variant(kind):
try:
inner()
except ValueError as e:
if kind == "implicit":
raise RuntimeError("ticket row failed")
if kind == "from e":
raise RuntimeError("ticket row failed") from e
raise RuntimeError("ticket row failed") from None
for kind in ("implicit", "from e", "from None"):
try:
variant(kind)
except RuntimeError:
tb = traceback.format_exc()
marker = next(
(line.strip() for line in tb.splitlines()
if "exception was" in line or "During handling" in line),
"(chain hidden)",
)
print(f"3. {kind:9} -> {marker}")
# 4. finally overriding a return — discards the result AND in-flight exceptions
def compute():
try:
return "try result"
finally:
return "finally wins"
def compute_raise():
try:
raise ValueError("boom")
finally:
return "finally wins"
print("4. finally beats return:", compute(), "|", compute_raise(), "(exception gone)")
# 5. except Exception around everything hides real bugs
orders = [{"price": 9.99}, {"price": 4.50}]
def buggy_total(items):
try:
return sum(i["prize"] for i in items) # typo: 'prize' not 'price'
except Exception:
return 0.0
print("5. broad except hid a KeyError bug -> total:", buggy_total(orders))
# 6. logging a secret: it lands in every sink the handler writes to
logging.basicConfig(level=logging.INFO,
format="%(levelname)s %(name)s: %(message)s", stream=sys.stdout)
log = logging.getLogger("gallery")
password = "hunter2" # placeholder stand-in for a real credential
log.info("db connect as admin, password=%s", password) # the sin
log.info("db connect as admin, password=%s", "********") # the fix1. bare except caught SystemExit(3) — KeyboardInterrupt dies here too
2. swallowed -> loaded: [4, 7] (no error, no log, no trace)
3. implicit -> During handling of the above exception, another exception occurred:
3. from e -> The above exception was the direct cause of the following exception:
3. from None -> (chain hidden)
4. finally beats return: finally wins | finally wins (exception gone)
5. broad except hid a KeyError bug -> total: 0.0
INFO gallery: db connect as admin, password=hunter2
INFO gallery: db connect as admin, password=********(On Python 3.14+ this file also emits SyntaxWarning: 'return' in a 'finally' block at compile time — PEP 765 made the interpreter itself flag sin 4.)
- Bare
except:catchesBaseException—sys.exit(3)andKeyboardInterruptincluded — so "handle everything" quietly means "swallow everything, including the user pressing Ctrl+C". Name the exceptions you mean (3.2). - Swallowed exceptions —
except ValueError: passdeleted"oops"without a trace: no error, no log, no record. Catch only when you can do something — log, collect the error, re-raise, or return a defined fallback (3.4). - Losing the traceback — the three re-raise styles tell three different stories: implicit chaining shows "During handling...",
from eshows "direct cause",from Nonehides the chain entirely. Pick deliberately;e.add_note()adds context without wrapping (2.3). finallyoverridingreturn—compute_raise()returned"finally wins"and theValueError("boom")never surfaced.finallyis for cleanup, not control flow — theSyntaxWarningnote above is the language agreeing.except Exceptionaround everything — theKeyErrorfrom the"prize"typo became a plausibletotal: 0.0; the bug shipped silently. Broad catches belong at boundaries around code you don't control, not wrapped around your own logic (Part 5).- Logging secrets —
password=hunter2landed in the log stream; every sink the handler writes to now holds the credential. Log fields and hashes; secrets and PII stay out by default (7.7).
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A program that runs without errors is correct." | Only proves nothing crashed. Logic errors produce plausible wrong answers — that's what tests and review are for. |
"except: catches everything, which is safest." |
It catches KeyboardInterrupt, SystemExit and GeneratorExit too, and except Exception: pass hides failures silently. Name the exceptions you mean. |
"Checking first (if key in d) prevents errors." |
The check and the use aren't atomic — the key can vanish between them. EAFP inside try is the race-free form. |
"finally always runs, so put cleanup there and forget it." |
True — but a return inside finally silently discards the try result and any in-flight exception. Cleanup, not control flow. |
| "Catch the error where it happens." | Catch where you can do something with it — often that's the boundary, not the crash site. Libraries raise; applications handle. |
| "Logging the full request helps debugging." | It also logs PII, secrets and user data into long-retention stores. Log fields and hashes; content behind a flag, redacted. |
"print is fine for errors — it's all stderr anyway." |
print goes to stdout. Diagnostics belong on stderr via logging, or they corrupt piped/JSON output. |
"assert validates input." |
python -O strips every assert. Asserts are internal invariants and test assertions — never security or input checks. |
| "A traceback means the program is broken beyond repair." | A traceback is information: which frame, which expression, which exception. Read bottom-up for cause, top-down for journey. |
| "Retrying is always safe." | Only transient errors, only with a cap/backoff, only for idempotent operations — a retried POST can double-charge. |
"More try/except makes code more robust." |
Over-defensive code hides bugs. Validate at boundaries, trust types inside, let unexpected errors reach a handler that logs them. |
Key takeaways#
- Three error kinds: syntax (won't parse), runtime/exception (crashes mid-run, with a traceback), logic (runs fine, wrong answer — only tests catch it).
- The exception hierarchy:
BaseException→Exception→ specific classes. CatchException, neverBaseException; orderexceptclauses specific-first. - Read tracebacks bottom-up: last line is the exception type+message; frames above are the call path;
~~~~^^carets mark the exact failing expression (3.11+). try/except/else/finally: risky code intry, success follow-up inelse, guaranteed cleanup infinally. Bareexcept:andexcept: passare sins.- EAFP over LBYL: try the operation, catch the failure — checking first isn't atomic and duplicates the lookup.
- Chain deliberately:
raise New(...) from efor "this replaces that"; implicit chaining otherwise;e.add_note()for context without wrapping. - Custom exceptions: one
AppErrorroot, themed subclasses, structured attributes — the shape provider SDKs use. withis guaranteed cleanup:__enter__/__exit__,@contextmanagergenerators,ExitStackfor dynamic sets,suppressfor visible ignoring.- Design: catch where you can act, propagate where you can't; validate once at boundaries; libraries raise, applications handle; log-then-re-raise at edges.
- Debug:
f"{x=}"and!rfor honest prints;breakpoint()/pdbfor stepping;tracebackmodule for formatting caught errors;-X dev/-W error/faulthandlerto expose hidden bugs; bisect and minimise. - Log, don't print: named loggers via
getLogger(__name__), levels, handlers for destinations, lazy%sargs,logger.exceptionfor tracebacks — and never log secrets or PII. - The triage loader: per-row
TicketParseError,try_parsethat never raises, collected errors, logged skips — the pattern every batch job needs.
Where you'll use this in the AI path#
| Skill from this lesson | Used in |
|---|---|
| Catching provider exceptions by type, specific-first | 03.8, 3.7 and the classifier in 4.4 |
| Retry only transient failures, with caps | 03.8, Part 4, 01B.9, 11C.3 |
| Validating model output at the boundary | 03.4, Part 6-7 — schema validation is boundary validation |
| Structured call logging, correlation IDs | 03.10, Part 4, 11A.1 |
| Debugging "what did we actually send?" | 03.10, Part 3 |
| Never logging prompts/PII | 12.4, 03.10, 4.1 |
| Minimal reproductions for bug reports | 00.9, 4.3, 03.10, Part 5 |
asyncio.TaskGroup + except* |
01B.3, 03.9 |
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Syntax error | A parse failure — the file can't run at all (SyntaxError, IndentationError) |
| Runtime error / exception | A failure raised while code runs, reported as a traceback |
| Logic error | Wrong output with no crash — invisible without tests |
| Traceback | The report of the call stack and exception that ended (or was caught in) a run |
| Exception hierarchy | BaseException → Exception → specific classes like ValueError, KeyError |
try/except/else/finally |
The four clauses: risky code, handlers, success path, guaranteed cleanup |
| EAFP / LBYL | "Ask Forgiveness" (try and catch) vs "Look Before You Leap" (check first) |
| Exception chaining | Linking a new exception to the one being handled (raise ... from, implicit chains) |
| Custom exception | A user-defined exception class, usually under an AppError root |
ExceptionGroup / except* |
Bundling several exceptions; matching subgroups by type (3.11+) |
warnings |
Non-fatal alerts via warnings.warn; filters can escalate them to errors |
assert |
A sanity check removed by python -O — invariants, not validation |
sys.exit / exit code |
Raising SystemExit; 0 = success, non-zero = failure to the shell |
KeyboardInterrupt |
The exception Ctrl+C raises — catch to clean up, then re-raise |
| Context manager | An object with __enter__/__exit__ used via with for guaranteed cleanup |
@contextmanager |
Decorator turning a generator into a context manager |
ExitStack |
A stack of context managers entered dynamically, unwound in reverse |
contextlib.suppress |
A context manager that visibly ignores named exceptions |
breakpoint() / pdb |
The built-in debugger drop-in and the interactive debugger behind it |
faulthandler |
Dumps the Python stack on hard crashes or on demand |
| Logger / handler / formatter | The logging parts: named channel, destination, output template |
| Log level | DEBUG–CRITICAL threshold controlling which records are emitted |
| Last-resort handler | The built-in handler logging falls back to when no handler is configured: it prints only WARNING and above, as the bare message |
| Lazy log formatting | Passing %s args instead of f-strings so formatting only happens if emitted |
| Structured logging | Machine-readable log records (JSON/fields) for aggregation |
doctest |
Docstring examples that run as tests via python -m doctest |
add_note() / __notes__ |
Context strings attached to an exception (3.11+) and printed under the traceback, without wrapping it |
sys.excepthook |
The function Python calls for an exception that nothing caught; replaceable, for routing uncaught errors into logs |
Exercises#
- Traceback reading. Run the three scripts from Part 2 (
tb_callstack.py,tb_implicit2.py,tb_explicit.py) and study their tracebacks. For each, write one sentence naming the frame where the fix belongs and why. - Exception taxonomy.
taxonomy.py(below) shows theshow()helper pattern — addshow("label", fn)calls to trigger three more built-ins:RecursionError(a function that calls itself with no stopping condition:def f(): return f(), then callf()on its own line),OverflowError(float(10**1000)), andUnicodeDecodeError(b"\xff".decode()). Printtype(e).__name__for each. (StopAsyncIteration, raised byanexton an async iterator, is the fourth — you'll meet it properly with async in 01B.3.)
taxonomy.py — the model script
# taxonomy.py — trigger each common built-in exception and print its type
def show(label, fn):
try:
fn()
except Exception as e:
print(f"{label:28} -> {type(e).__name__}: {e}")
show("undefined name", lambda: undefined_name) # noqa: F821
show("str + int", lambda: "a" + 1)
show("missing dict key", lambda: {"a": 1}["b"])
show("list index", lambda: [1, 2][5])
show("missing attribute", lambda: "x".no_such_method)
show("missing file", lambda: open("no-such-file.txt"))
show("divide by zero", lambda: 1 / 0)
show("int('abc')", lambda: int("abc"))
show("bad import", lambda: __import__("no_such_module_xyz"))
show("stop iteration", lambda: next(iter([])))- EAFP vs LBYL. Write
get_nested(d, *keys)that returnsNoneon any missing key — once withif key in dchecks, once withtry/except KeyError. Which is shorter? Which survives a dict mutated mid-call? - Chaining. Write
load_user(path)(useimport jsonandjson.loads(text)on a deliberately broken string such as"{bad"; 01A.9 teachesjsonproperly) that catchesjson.JSONDecodeErrorand raisesConfigError— first implicitly, then withfrom e, then withfrom None. Diff the three tracebacks and say when each is right. - Custom hierarchy. Extend
custom_exc.py's tree withTicketStoreErrorraised by a fakesave_ticket()that fails onNoneinput. CatchAppErrorinmainand printe.__class__.__name__. - Context manager. Write
@contextmanager def timed(label)that yields nothing and prints elapsed in afinally. Use it around aforloop that raisesValueErrorhalfway — confirm the timing line still prints. - ExitStack. Using the
Resourceclass fromexitstack.py, open three resources where the middle one raises on__enter__. Which resources get closed, and in what order? - Debug practice.
pdb_target.pyhas the discount bug. Reproduce it, then fixtotal_priceand provetotal=180.0. Save the corrected one-liner. - Logging. Convert
print_debug.py's probes intologgingcalls atDEBUGlevel, run once withlevel=INFO(silent) and once withDEBUG(visible). Show both outputs. - Rotating logs. In
log_rotate.py, changebackupCountto 1 andmaxBytesto 100. Predict the file set before running, then verify. - Robust loader. Add a fifth rule to
triage_load.py: reject rows wherestatusisn't in{"open","in_progress","closed"}. Add a CSV row that violates it, run, and show the new error line. try_parsecontract. Write a test (plainasserts inif __name__ == "__main__") asserting that for every row inCSV_TEXT, exactly one of(ticket, error)is notNone, and thatlen(tickets) + len(errors) == 8.- Debugging a broken program. This snippet silently loses rows — find and fix the bug without running it first:
for row in rows:
try:
tickets.append(parse_row(row))
except TicketParseError:
continue
finally:
tickets.clear() # <-- suspect- Warnings. Run
python3 -W error::UserWarning warn_demo.py-style escalation against your ownwarnings.warncall. At what point does the warning become an exception, and what exit code results? - Exit codes. Write
main(argv)for a CLI that takes one input path, and exits0on--help(and on success),2on a missing required argument, and1on unexpected errors such as a missing file. Do it withsys.argvandsys.exit(main(sys.argv[1:]))— noargparseneeded. Verify every case withecho $?(echo %ERRORLEVEL%in Windowscmd).
Solutions
- Traceback reading: (a)
tb_callstack.py— the crash is inparse_ticket(int("high")), but the fix belongs where the data contract is decided: eitherparse_ticketstops assuming field 2 is numeric (map"high"to a number, or validate and raise a typed error), orload_onevalidates the line before parsing;mainis only the messenger. (b)tb_implicit2.py— the root cause is the bad cell ('notanumber'), but the code defect is inload_ticket'sexceptblock: it raisesRuntimeErrorwithoutfrom e, so the reader gets the confusing "During handling..." wording; addfrom e. (c)tb_explicit.py— the code is already right (from eshows the cause); the fix is outside the function: create or point to the missing config file, or catchConfigErroronce at the top level and exit with a clear message. The point: the last line tells you what happened; the frames tell you whose contract broke. RecursionErrorviadef f(): return f()followed by a separatef()call (on one line,return f(); f()would put the second call inside the function body, sofwould never be called) — theshow()helper printsRecursionError: maximum recursion depth exceeded;OverflowErrorviafloat(10**1000)→OverflowError: int too large to convert to float;UnicodeDecodeErrorviab"\xff".decode("utf-8")→'utf-8' codec can't decode byte 0xff. (Run them to see exact messages.)- EAFP version — shorter and correct under mutation:
def get_nested(d, *keys):
try:
for k in keys:
d = d[k]
except (KeyError, TypeError):
return None
return d(LBYL's if k in d checks can pass and then fail the access if the dict mutates mid-call.)
4. Implicit: "During handling..."; from e: "direct cause"; from None: clean single traceback — right when the JSON error is noise.
5. save_ticket(None) raises TicketStoreError("ticket must not be None"); main catches AppError and prints TicketStoreError.
6. The timed context manager:
from contextlib import contextmanager
import time
@contextmanager
def timed(label):
start = time.perf_counter()
try:
yield
finally:
print(f"{label}: {time.perf_counter() - start:.4f}s")The finally print runs even though ValueError propagated — that's the guarantee working.
7. db opens, cache's __enter__ raises → db.__exit__ runs (LIFO unwind of what was entered); cache itself never entered so nothing to close for it; resources after the failure never open.
8. return price * qty * (1 - discount) → total=180.0.
9. log.debug("target=%r tags=%r", target, target["tags"]) — silent at INFO, visible at DEBUG.
10. With maxBytes=100, backupCount=1: at most two files, app.log (newest) + app.log.1 (previous); older deleted.
11. Inside parse_row, after the priority checks:
if _cell(raw, "status") not in {"open", "in_progress", "closed"}:
raise TicketParseError(row_number, _cell(raw, "status"), "bad status")…plus T-1009,Broken status,2,weird in CSV_TEXT → a new ERR row 10: bad status (raw='weird') line and 5 bad rows in the summary (the cell is passed as raw, same as the priority errors).
12. The try_parse contract test:
# appended to triage_load.py (or a test file importing it)
rows = list(csv.DictReader(io.StringIO(CSV_TEXT)))
assert len(rows) == 8
for n, raw in enumerate(rows, start=2):
ticket, error = try_parse(n, raw)
assert (ticket is None) != (error is None), f"row {n} broke the contract"All deterministic — runs for real.
13. The finally: tickets.clear() runs on every iteration including successful appends — wiping the list each loop. Move cleanup out of the loop or delete it.
14. The warning raises at the warnings.warn call site; traceback shows it; exit code 1.
15. main returns the code and the if __name__ == "__main__": line passes it to sys.exit, the same pattern as exit_demo.py in Part 3. A complete version (all four runs were executed for real):
# cli15.py — exit codes: 0 for --help and success, 2 for usage errors, 1 for unexpected failures
import sys
USAGE = "usage: cli15.py INPUT.csv"
def run(path):
with open(path, encoding="utf-8") as f: # may raise FileNotFoundError
print(f"read {len(f.readlines())} lines from {path}")
def main(argv):
if "--help" in argv:
print(USAGE)
return 0
if not argv: # required argument missing
print(f"error: INPUT.csv is required\n{USAGE}", file=sys.stderr)
return 2
try:
run(argv[0])
except Exception as e: # top-level catch: report, non-zero exit
print(f"error: {type(e).__name__}: {e}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))Output (for --help, no argument, missing.csv, and a two-line in.csv, each followed by echo $?):
usage: cli15.py INPUT.csv
exit=0
error: INPUT.csv is required
usage: cli15.py INPUT.csv
exit=2
error: FileNotFoundError: [Errno 2] No such file or directory: 'missing.csv'
exit=1
read 2 lines from in.csv
exit=0(Exit code 2 for "bad usage" is the convention argparse follows too — 01B.10 and the triage CLI in 01A.10 use it.)
Check yourself#
- Name the three kinds of errors and which one a traceback cannot detect.Syntax, runtime (exception), logic. A traceback can't detect a logic error — nothing crashes.
- Why should
exceptclauses be ordered specific-first?Becauseexceptmatches subclasses: a broad clause placed first shadows the specific ones below it. - What's the difference between
elseandfinallyin atry?elseruns only whentrysucceeded (keeps follow-up errors out of your handlers);finallyruns always (cleanup). - Why is
except:(bare) dangerous, and what does it catch thatexcept Exceptiondoesn't?BareexceptcatchesBaseException—KeyboardInterrupt,SystemExit,GeneratorExit— and pairs withpassto hide everything. - When is implicit exception chaining shown as "During handling..." vs "direct cause"?Implicit ("During handling") when you raise inside
exceptwithoutfrom; "direct cause" when you useraise ... from e. - EAFP vs LBYL — give one case where LBYL is genuinely better.When "absent" is normal data, not an error — e.g.
.get()for optional fields, or when the check itself is the business logic. - What does
raise(bare) insideexceptdo thatraise NewError(...)doesn't?Bareraisere-raises the same exception with its original traceback;raise NewErrorstarts a new exception (and chains implicitly unlessfrom). - Why derive custom exceptions from an
AppErrorbase rather thanExceptiondirectly?Soexcept AppErrorcatches all deliberate app failures whileexcept Exceptionstill catches the unexpected — callers can distinguish "expected domain error" from "bug". - In
with cm as x, which method's return value binds tox, and which runs on exception?__enter__'s return binds tox;__exit__runs on both paths and gets(exc_type, exc, tb). ExitStackexits run in what order, and what doessuppressinside it do to earlier exits?LIFO (reverse order of entry); oncesuppresshandles the exception, earlier exits seeexc=None.- Why is
log.debug(f"x={x}")worse thanlog.debug("x=%s", x)?The f-string formats eagerly even when DEBUG is off;%sargs are only interpolated if the record is emitted. - What are the two things you must never put in a log line by default?Secrets/credentials and PII (prompts, user data) — logs leak.
- What's the difference between
assertand input validation?assertis stripped bypython -Oand documents invariants; validation must run in production, so it needs real checks/exceptions. - In the triage loader, why does
try_parsereturn a tuple instead of raising?So per-row failures become data the caller collects — one bad row can't kill the batch; the error object carries row/reason for reporting. - A retried LLM call fails with the same error every time. Which Part 5 rule did the retry violate?"Only retry transient failures" — a deterministic error (bad request, invalid schema) will fail identically every time; fix the request, don't retry.
Further resources#
- Python docs: Exceptions — the built-in exception hierarchy, the reference table.
- Python docs:
trystatement / Errors and Exceptions tutorial — the language tutorial's treatment. - What's New in Python 3.11 — PEP 657 (fine-grained tracebacks), PEP 654 (
ExceptionGroup/except*), PEP 678 (add_note). - What's New in Python 3.13 and 3.14 — coloured tracebacks (
PYTHON_COLORS,NO_COLOR,FORCE_COLOR) and improved error messages. - Python docs:
loggingandlogging.handlers— handlers,RotatingFileHandler,dictConfig. - Python docs:
pdb— the full debugger command list. - Python docs:
traceback,warnings,contextlib,faulthandler,doctest— the modules used here. - Python docs: Command line and environment —
-X dev,-W,PYTHONBREAKPOINT,PYTHONNODEBUGRANGES. - PEP 657 (peps.python.org/pep-0657) and PEP 654 (peps.python.org/pep-0654) — the design documents.
- Python release schedule: python.org/downloads and the devguide versions page — check end-of-life dates before pinning.
← 01A.7 — Modules, Packages, Imports and a Tour of the Standard Library | Module 01A overview | 01A.9 — Files, Paths, JSON and CSV →