🐍 Python for Everyone

← Back to all chapters

Chapter 26 of 33 Intermediate 90 min read

Debugging Production Issues

Every earlier chapter taught you how to write Python that works. This chapter is different on purpose: it's a scannable field guide to Python that breaks — real symptoms you'd actually see in a log file or a bug report, the mechanism that causes each one, the fix, and a minimal repro you can run yourself. It's built as a catalog, not a story with a beginning and end, so jump to whatever category matches the problem in front of you.

How to read this chapter

Chapter 12 taught you try/except as a mechanism. This chapter is about the other half of that skill: recognizing which exception a piece of broken code is about to throw, before it throws it — the pattern-matching real debugging actually runs on.
Category 1 of 8

1. Crashes & Exceptions

Ten real crash patterns, each one traceable to a specific earlier chapter's feature. Every traceback below is the actual, unedited output of running that exact code.

#1

KeyError: 'DATABASE_URL'

Symptom

The service crashes on startup, before it ever handles a single request, with a KeyError pointing at a config key.

Root cause

Chapter 8 covered that some_dict[key] raises KeyError the instant the key isn't present — there's no "closest match" or silent fallback. A hardcoded config dict is missing a key that a deployment step (an environment variable, a secrets file) was supposed to provide.

Fix

Use config.get("DATABASE_URL") with an explicit fallback or a clear startup-time error message, instead of letting a raw KeyError (which doesn't say why the key is missing) surface as the crash.

issue_01_keyerror.py
config = {"HOST": "localhost", "PORT": 5432}

def connect():
    db_url = config["DATABASE_URL"]
    return f"Connecting to {db_url}"

print(connect())
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_01_keyerror.py", line 7, in <module>
    print(connect())
          ~~~~~~~^^
  File "issue_01_keyerror.py", line 4, in connect
    db_url = config["DATABASE_URL"]
             ~~~~~~^^^^^^^^^^^^^^^^
KeyError: 'DATABASE_URL'

Thought process: the fix isn't just "use .get()" — it's deciding whether a missing DATABASE_URL should have a sane default (fine for HOST/PORT) or should fail loudly and immediately (right for something the service can't run without). An experienced dev treats those as two different cases, not one blanket "always use .get()" rule.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function load_config(config, required_keys) that checks a dict against a list of required key names. For any key that's missing, raise a RuntimeError with a message listing every missing key at once (not just the first one found) so a developer sees the whole problem in one run instead of fixing keys one at a time. If nothing is missing, return the dict unchanged.
#2

IndexError: list index out of range

Symptom

A report-generation function crashes intermittently — it works for most inputs, then suddenly fails with IndexError once a list is shorter than expected.

Root cause

Chapter 5 covered that range(n) doesn't know or care how long any particular list is — this function assumes there are always at least n items to loop over, and that assumption silently holds until the day the list is shorter.

Fix

Bound the loop by the list's own length: range(min(n, len(scores))), or loop over scores[:n] directly so the loop can never ask for an index that isn't there.

issue_02_indexerror.py
scores = [88, 92, 79, 95]

def bonus_for_top_n(scores, n):
    total = 0
    for i in range(n):
        total += scores[i]
    return total

print(bonus_for_top_n(scores, 5))
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_02_indexerror.py", line 9, in <module>
    print(bonus_for_top_n(scores, 5))
          ~~~~~~~~~~~~~~~^^^^^^^^^^^
  File "issue_02_indexerror.py", line 6, in bonus_for_top_n
    total += scores[i]
             ~~~~~~^^^
IndexError: list index out of range
#3

A bare except: silently hides a typo, forever

Symptom

A settings loader "works" — it never crashes, and it always returns a default timeout of 30. Except it's always returning the default, even for configs where a real value was actually provided, and nobody notices for months.

Root cause

Chapter 12 covered that a bare except: catches every exception, not just the one you had in mind. Here the config key is typo'd ("timeoout"), which raises a KeyError — and the bare except: quietly swallows it and returns the fallback, exactly as if the key had simply been left out on purpose. The typo becomes invisible.

Fix

Catch the specific exception you actually expect (except KeyError:), never a bare except: — that way a genuine typo or unrelated bug still surfaces as its own distinct crash instead of being silently absorbed into "using the default."

issue_03_bare_except.py
def load_settings(raw):
    try:
        return int(raw["timeout"])
    except:
        return 30

# a typo in the config key -- "timeoout", not "timeout"
print(load_settings({"timeoout": "45"}))
actual output (Python 3.14.4)
30

Nothing here looks broken — the function runs, returns a plausible number, and never raises. That's exactly the danger: change except: to except KeyError: and run it again, and the real bug (a typo'd key that means the configured timeout of 45 is never actually used) finally surfaces as a visible KeyError instead of hiding behind a fallback value forever.

#4

TypeError: unsupported operand type(s) for /: 'str' and 'int'

Symptom

A checkout function crashes with a TypeError several function calls deep — the traceback points at a line of ordinary-looking arithmetic.

Root cause

Chapter 2 covered that Python is dynamically typed — nothing stops a caller from passing a string where a number was expected. Here percent_off arrives as the string "10" (likely straight from form input or a query parameter) and gets passed through two function calls before the arithmetic finally fails, far from where the bad value actually originated.

Fix

Convert and validate external input at the boundary where it enters the system (right after reading it from a form/request), not deep inside business logic — by the time apply_discount() runs, percent_off should already be guaranteed numeric.

issue_04_typeerror.py
def apply_discount(price, percent_off):
    return price - (price * percent_off / 100)

def checkout_total(price, percent_off):
    return apply_discount(price, percent_off)

# percent_off arrived as a string, e.g. straight from request.form
print(checkout_total(100, "10"))
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_04_typeerror.py", line 7, in <module>
    print(checkout_total(100, "10"))
          ~~~~~~~~~~~~~~^^^^^^^^^^^
  File "issue_04_typeerror.py", line 5, in checkout_total
    return apply_discount(price, percent_off)
  File "issue_04_typeerror.py", line 2, in apply_discount
    return price - (price * percent_off / 100)
                    ~~~~~~~~~~~~~~~~~~~~^~~~~
TypeError: unsupported operand type(s) for /: 'str' and 'int'
#5

AttributeError: 'NoneType' object has no attribute 'get'

Symptom

Sending a welcome email crashes with an AttributeError mentioning NoneType — a type that was never mentioned anywhere in the code that crashed.

Root cause

Chapter 10 covered that a function with no explicit return on some code path implicitly returns None on that path. find_user() only returns inside the loop when a match is found — if the loop finishes without matching, the function falls through and returns None, with nothing announcing that it happened.

Fix

Check for None right where the value comes back (if user is None: ...) before calling any method on it — or raise a clear, named exception from find_user() itself when no match exists, instead of returning None silently.

issue_05_attributeerror.py
users = [
    {"name": "Ana", "email": "ana@example.com"},
    {"name": "Beto"},
]

def find_user(name):
    for u in users:
        if u["name"] == name:
            return u
    # falls through here if nothing matched -- implicitly returns None

def send_welcome_email(name):
    user = find_user(name)
    return user.get("email").upper()

print(send_welcome_email("Carla"))
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_05_attributeerror.py", line 15, in <module>
    print(send_welcome_email("Carla"))
          ~~~~~~~~~~~~~~~~~~^^^^^^^^^
  File "issue_05_attributeerror.py", line 13, in send_welcome_email
    return user.get("email").upper()
           ^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'get'
#6

A custom exception gets raised correctly -- and swallowed anyway

Symptom

A withdrawal of $200 from a $50 balance is reported as successful, with the balance left unchanged at $50 — no error, no warning, and no money actually moved (which is the only reason this bug is survivable at all).

Root cause

Chapter 12 covered writing custom exception classes specifically so callers can react to meaningful, named failures. InsufficientFundsError is raised correctly here — but the caller's except Exception: is broad enough to catch it too, right alongside genuine bugs, and silently falls back to "return the balance unchanged" as if nothing happened.

Fix

Catch the specific custom exception (except InsufficientFundsError:) and handle it deliberately — show the user a real "insufficient funds" message — instead of catching Exception broadly and treating every possible failure the same way.

issue_06_swallowed_custom_exception.py
class InsufficientFundsError(Exception):
    pass

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(f"Cannot withdraw {amount}, balance is {balance}")
    return balance - amount

def process_withdrawal(balance, amount):
    try:
        return withdraw(balance, amount)
    except Exception:
        return balance

result = process_withdrawal(50, 200)
print(f"Balance after withdrawal attempt: {result}")
actual output (Python 3.14.4)
Balance after withdrawal attempt: 50

The output looks completely reasonable in isolation — it's only wrong once you know a $200 withdrawal was silently rejected instead of clearly refused. This is the same shape of bug as #3: a too-broad except turning a real, specific failure into indistinguishable "normal" behavior.

#7

RecursionError: maximum recursion depth exceeded

Symptom

A recursive countdown function crashes with a huge traceback ending in RecursionError, instead of just counting down and stopping.

Root cause

Chapter 10 covered that every recursive function needs a base case that's actually reachable. countdown()'s base case checks n != 0 — but called with a negative starting number, n counts -5, -6, -7, ... and steps straight past 0 without ever landing exactly on it, so the base case never triggers.

Fix

Use a base case that can't be skipped over, such as n <= 0 instead of n != 0 — or validate the input and reject a negative starting value before recursion begins at all.

issue_07_recursionerror.py
def countdown(n):
    print(n)
    if n != 0:
        countdown(n - 1)

countdown(-5)
actual output (Python 3.14.4, truncated)
-5
-6
-7
...
  File "issue_07_recursionerror.py", line 4, in countdown
    countdown(n - 1)
    ~~~~~~~~~^^^^^^^
  [Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
#8

ZeroDivisionError: division by zero

Symptom

Computing a product's average rating crashes with ZeroDivisionError — but only for products that don't have any reviews yet.

Root cause

Chapter 3 covered that / raises ZeroDivisionError whenever the denominator is exactly 0 — no rounding, no special case. num_reviews here comes from a data source (this stands in for a real API/database result, tying back to Chapter 19) that's a perfectly valid 0 for a brand-new product, but the function never checks for it.

Fix

Check the denominator before dividing and return a sensible value for the zero case — 0, None, or "No reviews yet", whichever fits how the result gets displayed — instead of letting the division itself decide by crashing.

issue_08_zerodivisionerror.py
def average_rating(total_score, num_reviews):
    return total_score / num_reviews

# a brand-new product with no reviews yet
review_data = {"total_score": 47, "num_reviews": 0}
print(average_rating(review_data["total_score"], review_data["num_reviews"]))
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_08_zerodivisionerror.py", line 6, in <module>
    print(average_rating(review_data["total_score"], review_data["num_reviews"]))
          ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "issue_08_zerodivisionerror.py", line 2, in average_rating
    return total_score / num_reviews
           ~~~~~~~~~~~~^~~~~~~~~~~~~
ZeroDivisionError: division by zero
#9

FileNotFoundError and PermissionError look similar -- and aren't

Symptom

A log reader was written to handle "the file doesn't exist yet" gracefully. In production it crashes anyway — not because the file is missing, but because the process doesn't have permission to read it.

Root cause

Chapter 13 covered handling FileNotFoundError around open(). That's a different, more specific exception than PermissionError (raised when the file exists but the OS denies access — a locked-down production deploy directory, for example). Code that only catches FileNotFoundError lets a real PermissionError propagate as an unhandled crash, and the two are easy to mentally lump together as "file problems" even though the fix for each is completely different.

Fix

Catch both explicitly, and handle them differently: FileNotFoundError usually means "treat this as empty/first run"; PermissionError usually means the deployment itself is misconfigured and should fail loudly with a message an operator can act on, not be silently absorbed.

issue_09_file_errors.py
def read_log(path):
    try:
        with open(path) as f:
            return f.read()
    except FileNotFoundError:
        return "no log file yet"

print(read_log("/var/log/myapp/nonexistent-2026-07-09.log"))
actual output (Python 3.14.4)
no log file yet

This particular run succeeds because the path genuinely doesn't exist. The bug only shows up in an environment where the path exists but is locked down — at that point, open() raises PermissionError instead, which this except FileNotFoundError: does not catch, and the crash propagates uncaught.

#10

json.decoder.JSONDecodeError: Expecting value

Symptom

Parsing an API response crashes with JSONDecodeError — not because the API sent malformed JSON, but because it didn't send JSON at all.

Root cause

Chapter 19 covered json.loads() and checking a response's status code before trusting its body. This code skips that check and assumes every response body is valid JSON — but a real outage, rate limit, or misconfigured URL often returns an HTML error page (a login redirect, a "503 Service Unavailable" page) instead, and json.loads() has no way to parse that as JSON.

Fix

Check response.status_code (or equivalent) before parsing, and wrap json.loads() in its own try/except json.JSONDecodeError so a non-JSON response produces a clear "the API returned something unexpected" error instead of a raw parser traceback.

issue_10_jsondecodeerror.py
import json

def parse_api_response(raw_text):
    data = json.loads(raw_text)
    return data["results"]

# what a downed API actually returned -- an HTML error page, not JSON
fake_response_body = "<html><body>Service Unavailable</body></html>"
print(parse_api_response(fake_response_body))
actual output (Python 3.14.4, standard-library json frames trimmed for length)
Traceback (most recent call last):
  File "issue_10_jsondecodeerror.py", line 8, in <module>
    print(parse_api_response(fake_response_body))
          ~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "issue_10_jsondecodeerror.py", line 4, in parse_api_response
    data = json.loads(raw_text)
  ...
  File "/usr/lib/python3.14/json/decoder.py", line 363, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Quick recap
  • Most production crashes trace back to an assumption that was true in testing and false in the real world: a key that's always present, a list that's always long enough, input that's always the right type, a denominator that's never zero.
  • A bare except: or an overly broad except Exception: doesn't prevent bugs — it hides them, often turning a loud, easy-to-diagnose crash into a silent wrong answer (issues #3 and #6).
  • Similarly-named exceptions (FileNotFoundError vs. PermissionError) can require genuinely different handling — catching one doesn't mean the other is covered.
In the Real World (Category 1)
Category 2 of 8

2. Performance

Ten real performance patterns — each one a "before" and "after" version of the same logic, both actually timed with time.perf_counter(). A few show a dramatic speedup; a few show a modest, honest one. Both are real, and knowing which kind of fix you're looking at matters: some of these are genuine Big-O improvements, others are removing small, repeated overhead that only adds up at scale.

#11

Checking membership against a growing list, over and over

Symptom

A "find duplicates" function that's fast on a small test list becomes noticeably slow once the real dataset has a few thousand items — and gets dramatically worse as the dataset grows, not just proportionally worse.

Root cause

Chapter 8 covered that checking item in some_list has to scan the list from the start until it finds a match (or reaches the end) — an O(n) operation. Doing that check inside a loop that runs n times makes the whole function O(n²): every new item re-scans an ever-growing list.

Fix

Use a set instead of a list for the membership check — Chapter 8 also covered that item in some_set is O(1) on average, regardless of how large the set gets.

issue_11_quadratic_membership.py
import time

def find_duplicates_slow(items):
    seen = []
    duplicates = []
    for item in items:
        if item in seen:  # O(n) list scan, called n times -> O(n^2)
            duplicates.append(item)
        else:
            seen.append(item)
    return duplicates

def find_duplicates_fast(items):
    seen = set()
    duplicates = []
    for item in items:
        if item in seen:  # O(1) average-case set membership
            duplicates.append(item)
        else:
            seen.add(item)
    return duplicates

data = list(range(5000)) + list(range(2000))

start = time.perf_counter()
find_duplicates_slow(data)
slow_time = time.perf_counter() - start

start = time.perf_counter()
find_duplicates_fast(data)
fast_time = time.perf_counter() - start

print(f"list-based (O(n^2)): {slow_time:.4f}s")
print(f"set-based (O(n)):    {fast_time:.4f}s")
actual output (Python 3.14.4) -- your own numbers will vary by machine
list-based (O(n^2)): 0.0972s
set-based (O(n)):    0.0008s

Thought process: the actual fix here isn't "sets are faster than lists" as a blanket rule — it's recognizing the specific access pattern (repeated membership checks against a growing collection) where the difference between O(1) and O(n) per check compounds into O(n) vs. O(n²) overall. An experienced dev looks for this exact shape: any in check inside a loop, against a collection that's also being built up inside that same loop.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function find_duplicates(items) that returns a list of every item that appears more than once in `items`, preserving the order duplicates are first re-encountered. Use a set (not a list) to track items already seen, so the membership check inside the loop stays O(1) average case instead of O(n) -- this needs to stay fast even on a list with tens of thousands of items.
#12

Inserting at the front of a list in a loop

Symptom

A function that reverses the order of a list by building it up one item at a time gets dramatically slower as the input grows, even though it's doing the same amount of "work" per item.

Root cause

Chapter 7 covered that list.insert(0, x) has to shift every existing element over by one to make room at the front — an O(n) operation. Calling it n times to build an n-item list makes the whole function O(n²), the same shape of problem as issue #11 but from a different list operation.

Fix

list.append() adds to the end in O(1) amortized time. Append everything in order, then call .reverse() once at the very end — one O(n) pass total, instead of n separate O(n) shifts.

issue_12_insert_front.py
import time

def reverse_order_slow(items):
    result = []
    for item in items:
        result.insert(0, item)  # O(n) shift, every single call
    return result

def reverse_order_fast(items):
    result = []
    for item in items:
        result.append(item)  # O(1) amortized
    result.reverse()  # one O(n) pass at the end
    return result

items = list(range(20000))

start = time.perf_counter()
a = reverse_order_slow(items)
slow_time = time.perf_counter() - start

start = time.perf_counter()
b = reverse_order_fast(items)
fast_time = time.perf_counter() - start

print(a == b)
print(f"insert(0, x) in a loop: {slow_time:.4f}s")
print(f"append then reverse():  {fast_time:.4f}s")
actual output (Python 3.14.4) -- your own numbers will vary by machine
True
insert(0, x) in a loop: 0.0824s
append then reverse():  0.0005s
#13

Recomputing the same expensive result over and over

Symptom

A checkout function that calculates tax for a shopping cart is slow specifically when the cart has many items from the same handful of regions — even though there's only a few distinct regions actually involved.

Root cause

Chapter 10 covered function calls as the unit of reusable work — but nothing about a function call automatically remembers a previous result. A tax-rate lookup was called once per cart item, even though the same region's rate was computed identically, from scratch, every single time it recurred.

Fix

Cache results in a dict (Chapter 8) keyed by the input that determines the result — here, the region. Look up the cache before doing the expensive work, and only do the work (and store it) the first time a given region is seen.

issue_13_repeated_recompute.py
import time

def slow_tax_lookup(region):
    # stands in for a genuinely expensive computation
    total = 0
    for _ in range(20000):
        total += 1
    return 0.08

def total_price_slow(cart, get_tax_rate):
    total = 0
    for item in cart:
        rate = get_tax_rate(item["region"])  # recomputed for every item
        total += item["price"] * (1 + rate)
    return total

def total_price_fast(cart, get_tax_rate):
    total = 0
    cache = {}
    for item in cart:
        region = item["region"]
        if region not in cache:
            cache[region] = get_tax_rate(region)
        total += item["price"] * (1 + cache[region])
    return total

cart = [{"price": 10, "region": "CA"} for _ in range(500)]

start = time.perf_counter()
total_price_slow(cart, slow_tax_lookup)
slow_time = time.perf_counter() - start

start = time.perf_counter()
total_price_fast(cart, slow_tax_lookup)
fast_time = time.perf_counter() - start

print(f"recompute every item: {slow_time:.4f}s")
print(f"cache by region:      {fast_time:.4f}s")
actual output (Python 3.14.4) -- your own numbers will vary by machine
recompute every item: 0.3718s
cache by region:      0.0007s

Thought process: caching is only a correct fix when the same input reliably produces the same output — the region's tax rate doesn't change mid-checkout, so caching by region is safe here. An experienced dev checks that assumption explicitly before reaching for a cache, since caching a result that legitimately changes between calls (a live stock price, a random value) would introduce a correctness bug, not just a performance win.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function total_price(cart, get_tax_rate) where cart is a list of dicts with "price" and "region" keys, and get_tax_rate(region) is an expensive function that returns a tax rate for a region. Cache the result of get_tax_rate() in a dict keyed by region, so it's only ever called once per distinct region across the whole cart, not once per item. Return the total price including tax.
#14

A nested loop to join two lists of records

Symptom

A function that attaches customer names to a list of orders works fine in testing with a handful of records, then times out once it's run against the real orders and customers tables.

Root cause

For every order, the code scans the entire customers list looking for a matching ID — an O(m) scan repeated n times, for O(n·m) overall. With a few thousand of each, that's tens of millions of comparisons for what should be a simple lookup.

Fix

Build a dict mapping customer ID to customer record once, up front (Chapter 8's dict/set-comprehension-friendly pattern), then look up each order's customer in O(1) instead of scanning — O(n + m) overall instead of O(n·m).

issue_14_nested_loop_lookup.py
import time

def enrich_orders_slow(orders, customers):
    enriched = []
    for order in orders:
        for customer in customers:  # full scan, for EVERY order
            if customer["id"] == order["customer_id"]:
                enriched.append({**order, "customer_name": customer["name"]})
                break
    return enriched

def enrich_orders_fast(orders, customers):
    customer_by_id = {c["id"]: c for c in customers}  # built once
    enriched = []
    for order in orders:
        customer = customer_by_id.get(order["customer_id"])
        enriched.append({**order, "customer_name": customer["name"] if customer else None})
    return enriched

customers = [{"id": i, "name": f"Customer {i}"} for i in range(2000)]
orders = [{"customer_id": i % 2000, "amount": 10} for i in range(2000)]

start = time.perf_counter()
a = enrich_orders_slow(orders, customers)
slow_time = time.perf_counter() - start

start = time.perf_counter()
b = enrich_orders_fast(orders, customers)
fast_time = time.perf_counter() - start

print(a == b)
print(f"nested loop (O(n*m)): {slow_time:.4f}s")
print(f"dict lookup (O(n)):   {fast_time:.4f}s")
actual output (Python 3.14.4) -- your own numbers will vary by machine
True
nested loop (O(n*m)): 0.1629s
dict lookup (O(n)):   0.0015s
#15

Recompiling the same regular expression on every call

Symptom

A log-scanning function using re.search() is a bit slower than expected on a large batch of lines — a real but modest overhead, not a dramatic one.

Root cause

Chapter 18 covered re.search(pattern, text) as a convenience function — internally, it still has to turn the pattern string into a compiled matcher before it can search. Called repeatedly with the same pattern string, that parsing step repeats every time (CPython does cache a small number of recently-used patterns internally, which is why this speedup is real but modest rather than dramatic).

Fix

Call re.compile(pattern) once, outside the loop, and call .search()/.match() on the resulting compiled pattern object instead — the parsing step happens exactly once no matter how many times it's used afterward.

issue_15_regex_recompile.py
import re
import time

PATTERN_STR = r"\d{3}-\d{3}-\d{4}"

def find_phone_numbers_slow(lines):
    found = []
    for line in lines:
        match = re.search(PATTERN_STR, line)  # parses PATTERN_STR every call
        if match:
            found.append(match.group())
    return found

def find_phone_numbers_fast(lines):
    compiled = re.compile(PATTERN_STR)  # parsed once
    found = []
    for line in lines:
        match = compiled.search(line)
        if match:
            found.append(match.group())
    return found

lines = [f"Contact: 555-{i:03d}-{i:04d} for details" for i in range(30000)]

# take the BEST of 5 runs for each version -- a single run's timing can be
# noisy (one-off system interference); best-of-several is more stable
def timed(fn, arg):
    start = time.perf_counter()
    result = fn(arg)
    return time.perf_counter() - start, result

slow_time, a = min((timed(find_phone_numbers_slow, lines) for _ in range(5)), key=lambda t: t[0])
fast_time, b = min((timed(find_phone_numbers_fast, lines) for _ in range(5)), key=lambda t: t[0])

print(a == b)
print(f"re.search() each time (best of 5): {slow_time:.4f}s")
print(f"re.compile() once (best of 5):     {fast_time:.4f}s")
actual output (Python 3.14.4, best of 5 runs each) -- your own numbers will vary by machine
True
re.search() each time (best of 5): 0.0267s
re.compile() once (best of 5):     0.0205s

A real speedup, but a modest one — not every fix in this category is a dramatic win, and it's worth being honest about which is which. re.compile() is still worth doing as a habit: it costs nothing, and the margin grows if the pattern is more complex than this one.

#16

Sorting an entire list just to read the largest value

Symptom

A "top score" function is noticeably slower than it needs to be on a large dataset, despite only ever using one value out of the whole result.

Root cause

sorted() is O(n log n) — it does the work of putting every element in order, even when the only thing the caller actually wants is the single largest one.

Fix

max() finds the largest value in a single O(n) pass, without sorting anything. Use the built-in that matches what's actually needed — max()/min() for one extreme value, sorted() only when the full order genuinely matters.

issue_16_sort_for_max.py
import time
import random

def top_score_slow(scores):
    ordered = sorted(scores)  # O(n log n) to sort everything...
    return ordered[-1]         # ...just to read the last element

def top_score_fast(scores):
    return max(scores)  # O(n)

scores = list(range(200000))
random.shuffle(scores)

start = time.perf_counter()
a = top_score_slow(scores)
slow_time = time.perf_counter() - start

start = time.perf_counter()
b = top_score_fast(scores)
fast_time = time.perf_counter() - start

print(a == b)
print(f"sorted()[-1]: {slow_time:.4f}s")
print(f"max():        {fast_time:.4f}s")
actual output (Python 3.14.4) -- your own numbers will vary by machine
True
sorted()[-1]: 0.0704s
max():        0.0092s
#17

Re-evaluating len() on every loop iteration

Symptom

A hand-written while loop summing a very large list is measurably slower than the equivalent for loop, even though both do the same O(n) amount of "real" work.

Root cause

This one isn't about Big-O — len() on a list is already O(1). It's about repeated small overhead: while i < len(items): calls len() fresh on every single iteration, and that function-call overhead adds up across millions of iterations even though each individual call is cheap.

Fix

Compute len(items) once, store it in a variable before the loop starts, and check against that variable instead — the list's length doesn't change during the loop here, so there's nothing to recompute.

issue_17_len_in_condition.py
import time

def sum_while_slow(items):
    total = 0
    i = 0
    while i < len(items):  # len() called fresh every iteration
        total += items[i]
        i += 1
    return total

def sum_while_fast(items):
    total = 0
    i = 0
    n = len(items)  # computed once
    while i < n:
        total += items[i]
        i += 1
    return total

items = list(range(2000000))

start = time.perf_counter()
a = sum_while_slow(items)
slow_time = time.perf_counter() - start

start = time.perf_counter()
b = sum_while_fast(items)
fast_time = time.perf_counter() - start

print(a == b)
print(f"len(items) every iteration: {slow_time:.4f}s")
print(f"len(items) computed once:   {fast_time:.4f}s")
actual output (Python 3.14.4) -- your own numbers will vary by machine
True
len(items) every iteration: 0.2065s
len(items) computed once:   0.1292s

Another honest, modest speedup — and a preview of why Chapter 5's plain for item in items: is usually preferable to a hand-rolled while loop with a manual index in the first place: it sidesteps this whole class of micro-overhead automatically.

#18

Re-reading the same file from disk, once per search term

Symptom

A function that counts how many times each of several search terms appears in a log file gets slower the more search terms are passed in — even though the file itself never changes between searches.

Root cause

Chapter 13 covered reading a file with open()/.read(). Disk I/O is slow relative to in-memory operations — re-opening and re-reading the entire file once per search term repeats that slow I/O work unnecessarily, when the file's contents haven't changed at all between calls.

Fix

Read the file into memory exactly once, then run every search against that in-memory string — I/O happens once regardless of how many search terms there are.

issue_18_reread_file.py
import time

def count_matches_slow(path, needles):
    counts = {}
    for needle in needles:
        with open(path) as f:  # re-opens and re-reads the file every time
            content = f.read()
        counts[needle] = content.count(needle)
    return counts

def count_matches_fast(path, needles):
    with open(path) as f:
        content = f.read()  # read once
    counts = {}
    for needle in needles:
        counts[needle] = content.count(needle)
    return counts

# set up a sample log file so this script is runnable on its own
with open("access.log", "w") as f:
    for i in range(5000):
        f.write(f"line-{i}\n")

needles = [f"line-{i}" for i in range(0, 500, 50)]

start = time.perf_counter()
a = count_matches_slow("access.log", needles)
slow_time = time.perf_counter() - start

start = time.perf_counter()
b = count_matches_fast("access.log", needles)
fast_time = time.perf_counter() - start

print(a == b)
print(f"re-read file per needle: {slow_time:.4f}s")
print(f"read file once:          {fast_time:.4f}s")
actual output (Python 3.14.4, run against a 5,000-line log file) -- your own numbers will vary by machine and disk
True
re-read file per needle: 0.0014s
read file once:          0.0005s
#19

Materializing a full list when the loop could stop early

Symptom

A "find the first value over a threshold" function is dramatically slower than it should be on a large dataset, even though it usually only needs to look at the first handful of values before finding a match.

Root cause

Chapter 17 covered generators as lazy, on-demand value production. A list comprehension does the opposite: it computes and stores every value up front, before the loop even starts — so even though the loop below it exits early once a match is found, all the other work (doubling every remaining number that's never even inspected) already happened.

Fix

Use a generator expression instead of a list comprehension when the consumer might stop early. A generator produces values one at a time, on demand — once the loop finds its match and returns, no further values are ever computed.

issue_19_materialize_generator.py
import time

def find_first_over_slow(numbers, threshold):
    doubled = [n * 2 for n in numbers]  # computes EVERY value up front
    for d in doubled:
        if d > threshold:
            return d
    return None

def find_first_over_fast(numbers, threshold):
    doubled = (n * 2 for n in numbers)  # lazy -- computes on demand
    for d in doubled:
        if d > threshold:
            return d
    return None

numbers = list(range(2000000))

start = time.perf_counter()
a = find_first_over_slow(numbers, 100)
slow_time = time.perf_counter() - start

start = time.perf_counter()
b = find_first_over_fast(numbers, 100)
fast_time = time.perf_counter() - start

print(a == b)
print(f"list comprehension (materializes all): {slow_time:.4f}s")
print(f"generator expression (lazy, stops early): {fast_time:.4f}s")
actual output (Python 3.14.4) -- your own numbers will vary by machine
True
list comprehension (materializes all): 0.2775s
generator expression (lazy, stops early): 0.0000s

The single biggest speedup in this category, and it's a direct callback to Chapter 25's generators-vs-lists comparison — the same underlying idea (don't build what you don't need) showing up as a memory win there and a speed win here.

#20

Checking membership against dict.keys() instead of the dict itself

Symptom

A filtering function using if key in some_dict.keys() is a little slower than the same check written without .keys() — small, but consistent and free to fix.

Root cause

Chapter 8 covered dict membership (key in some_dict) as already O(1) average case — it doesn't need .keys() at all. Writing .keys() explicitly adds an unnecessary view-object layer that in then has to go through, for no benefit.

Fix

Drop the .keys() — key in some_dict checks the keys by default, is exactly as correct, and has one less layer of indirection.

issue_20_keys_membership.py
import time

def filter_active_slow(user_ids, status_by_id):
    active = []
    for uid in user_ids:
        if uid in status_by_id.keys():  # unnecessary .keys()
            if status_by_id[uid] == "active":
                active.append(uid)
    return active

def filter_active_fast(user_ids, status_by_id):
    active = []
    for uid in user_ids:
        if uid in status_by_id:  # dict membership is already O(1)
            if status_by_id[uid] == "active":
                active.append(uid)
    return active

status_by_id = {i: ("active" if i % 2 == 0 else "inactive") for i in range(200000)}
user_ids = list(range(200000))

start = time.perf_counter()
a = filter_active_slow(user_ids, status_by_id)
slow_time = time.perf_counter() - start

start = time.perf_counter()
b = filter_active_fast(user_ids, status_by_id)
fast_time = time.perf_counter() - start

print(a == b)
print(f"'in dict.keys()': {slow_time:.4f}s")
print(f"'in dict':         {fast_time:.4f}s")
actual output (Python 3.14.4) -- your own numbers will vary by machine
True
'in dict.keys()': 0.0231s
'in dict':         0.0161s
Quick recap
  • Nested loops and repeated in checks against a growing list/being scanned are the classic sign of an accidental O(n²) algorithm — a set or dict almost always fixes it.
  • Not every fix is a Big-O improvement — some (regex compilation, avoiding .keys(), hoisting len() out of a loop) just remove small, repeated overhead, and it's worth knowing the difference.
  • Generators (Chapter 17) aren't just a memory optimization (Chapter 25) — they're also a speed win whenever a consumer might stop early, since unconsumed values are never computed at all.
In the Real World (Category 2)
Category 3 of 8

3. Memory Leaks

Python's garbage collector handles most memory management automatically — which is exactly why memory leaks here feel surprising when they happen. Every entry below is a way to keep an object reachable (and therefore un-collectible) long after it should have been forgotten.

#21

An unbounded module-level cache that never shrinks

Symptom

A service's memory usage climbs steadily over days of uptime and never comes back down, even during quiet periods — eventually the process is killed by the host for using too much memory.

Root cause

Chapter 8 covered dicts as a natural cache: check if a key exists, compute and store it if not. What it didn't warn about is that a dict at module scope lives for the entire lifetime of the process — every distinct user_id ever looked up adds one more entry that's never removed, so the cache's size is really just "total distinct requests since startup."

Fix

Bound the cache: use functools.lru_cache(maxsize=...) (issue #29 below), a time-based expiry, or an explicit eviction policy so the cache's size reflects "recently useful data," not "everything ever requested."

issue_21_unbounded_cache.py
_cache = {}

def get_user_profile(user_id, fetch_from_db):
    if user_id not in _cache:
        _cache[user_id] = fetch_from_db(user_id)
    return _cache[user_id]

def fake_db_lookup(user_id):
    return {"id": user_id, "name": f"User {user_id}"}

for uid in range(1, 200001):
    get_user_profile(uid, fake_db_lookup)

print(f"cached entries: {len(_cache)}")
actual output (Python 3.14.4)
cached entries: 200000

Thought process: a cache with no upper bound isn't really a cache — it's a memory leak with a friendlier name. The fix isn't "add a size limit" as an afterthought; it's deciding up front what "recently useful" means for this specific data, since that decision determines whether lru_cache, a TTL, or something custom is the right tool.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function get_user_profile(user_id, fetch_from_db) that caches results, but caps the cache at a fixed maximum number of entries using functools.lru_cache. Explain what happens to the oldest entries once the cache is full, so a long-running process handling millions of distinct user_ids over its lifetime never grows its memory usage without bound.
#22

A reference cycle that survives until the garbage collector runs

Symptom

Objects that should be destroyed the moment they go out of scope stick around instead — a tree of parent/child objects doesn't get cleaned up immediately after the code that built it returns.

Root cause

Chapter 25 covered that CPython primarily uses reference counting: an object is freed the instant its reference count hits zero. A parent that holds a reference to its child, while the child holds a reference back to its parent, creates a cycle — each object's count never reaches zero on its own, even after nothing outside the cycle refers to either one. Only the separate, periodic cyclic garbage collector (gc) can break cycles like this, and it doesn't run instantly.

Fix

Break the cycle deliberately — store the child-to-parent link as a weakref.ref instead of a normal reference (issue #30 below takes this further), so the parent can still be freed by simple reference counting the moment nothing outside the cycle needs it.

issue_22_circular_del.py
import gc

class Node:
    def __init__(self, name):
        self.name = name
        self.parent = None
        self.children = []

    def __del__(self):
        print(f"Node {self.name} destroyed")

def build_tree():
    root = Node("root")
    child = Node("child")
    root.children.append(child)
    child.parent = root  # circular reference: root -> child -> root
    return root

gc.disable()
build_tree()
print("build_tree() returned, but no destruction message printed yet")
gc.enable()
gc.collect()
print("after gc.collect(), the cycle is finally cleaned up")
actual output (Python 3.14.4)
build_tree() returned, but no destruction message printed yet
Node root destroyed
Node child destroyed
after gc.collect(), the cycle is finally cleaned up

With gc enabled (the default), CPython's cyclic collector runs periodically on its own and would eventually catch this — the danger in a real long-running service is the gap between "logically unreachable" and "actually collected," during which every leaked cycle's memory stays held.

#23

An event listener that's registered but never unregistered

Symptom

A UI or event-driven service's memory grows in proportion to how many short-lived objects have ever been created, not how many currently exist — even objects the rest of the program has completely forgotten about.

Root cause

Chapter 10 covered passing functions (including bound methods) as values. Subscribing self._on_event to an EventBus hands the bus a reference to the method — which keeps self alive too, since a bound method holds a reference to its instance. The caller can drop every other reference to a Widget, but as long as the bus's subscriber list still references its callback, the whole widget (and everything it holds, like self.data) stays alive.

Fix

Provide (and actually call) an unsubscribe()/disconnect() method when an object is done with an event bus — or have the bus hold subscribers as weakrefs so a widget with no other references can still be collected even if it forgot to unsubscribe.

issue_23_event_listeners.py
class EventBus:
    def __init__(self):
        self._listeners = []

    def subscribe(self, callback):
        self._listeners.append(callback)

    def publish(self, event):
        for cb in self._listeners:
            cb(event)

class Widget:
    def __init__(self, bus, name):
        self.name = name
        self.data = [0] * 1_000_000  # something large, to make the leak visible
        bus.subscribe(self._on_event)

    def _on_event(self, event):
        pass  # widget reacts to events

bus = EventBus()

def create_and_discard_widget(n):
    w = Widget(bus, f"widget-{n}")
    return w  # caller drops the reference immediately after this returns

for i in range(50):
    create_and_discard_widget(i)

print(f"listeners still registered: {len(bus._listeners)}")
actual output (Python 3.14.4)
listeners still registered: 50
#24

A closure that captures a list and appends to it forever

Symptom

A "request logger" helper that's called once to set itself up appears simple and self-contained — but the process's memory grows steadily with every request it logs, for the life of the process.

Root cause

Chapter 9 covered closures: the inner log_request() function captures history from its enclosing scope and keeps a live reference to it. That's the entire point of a closure — but it means history lives exactly as long as log_request itself does, which here is the whole program, and nothing ever trims it.

Fix

Cap history's size explicitly (e.g. a collections.deque(maxlen=1000) instead of a plain list), or don't accumulate history in the closure at all — write each entry somewhere with its own retention policy (a log file, a database) instead of an ever-growing in-memory list.

issue_24_closure_capture.py
def make_request_logger():
    history = []  # captured by the closure below, grows forever

    def log_request(request_body):
        history.append(request_body)  # never trimmed or cleared
        return len(history)

    return log_request

log_request = make_request_logger()

# simulate handling 100,000 requests, each with a decent-sized body
for i in range(100_000):
    count = log_request("x" * 500)

print(f"requests remembered by the closure: {count}")
actual output (Python 3.14.4)
requests remembered by the closure: 100000
#25

A global list of "recent" errors that's never actually recent

Symptom

A worker process that's meant to keep a short list of recent errors "for the dashboard" ends up with a multi-gigabyte list after running for a few weeks.

Root cause

Chapter 4 and 5 covered append() as the basic way to build up a list — but nothing about append() automatically implies a size limit. The name recent_errors describes an intent, not an actual constraint the code enforces; every batch adds more entries, and the list quietly becomes "every error since the process started," not "recent" ones.

Fix

Use a bounded structure that enforces the intent in code, not just in the variable's name — collections.deque(maxlen=500) automatically drops the oldest entry once it's full, so "recent" stays true no matter how long the process runs.

issue_25_global_accumulator.py
recent_errors = []  # meant to hold "recent" errors only

def log_error(message):
    recent_errors.append(message)  # appended, but never trimmed

def process_orders(orders):
    for order in orders:
        if order["amount"] <= 0:
            log_error(f"invalid amount for order {order['id']}")

# a long-running worker process handling orders in batches, forever
for batch in range(3):
    bad_orders = [{"id": i, "amount": -1} for i in range(1000)]
    process_orders(bad_orders)

print(f"recent_errors has grown to: {len(recent_errors)} entries, after just 3 batches")
actual output (Python 3.14.4)
recent_errors has grown to: 3000 entries, after just 3 batches
#26

File handles opened and never closed

Symptom

After a while, a service that writes many small report files starts crashing with OSError: Too many open files, seemingly at random.

Root cause

Chapter 13 covered open() and the with statement for automatic cleanup — but this code opens a file, does not use with, and additionally stores the handle in a list "to flush them all at shutdown." Each open file consumes one of the operating system's limited file-descriptor slots per process; without an explicit close(), those slots are never returned.

Fix

Always use with open(...) as f: so the file is closed automatically the moment the block exits, even if an exception happens inside it — and avoid keeping long-lived references to open file objects unless there's a real reason the file needs to stay open.

issue_26_unclosed_files.py
_open_report_handles = []  # a real bug: handles are kept here and never closed

def write_daily_report(day, lines):
    f = open(f"/tmp/ch26_report_{day}.txt", "w")  # never closed -- no f.close(), no "with" block
    _open_report_handles.append(f)  # e.g. kept around for a "flush all at shutdown" feature
    for line in lines:
        f.write(line + "\n")

for day in range(5000):
    write_daily_report(day, [f"entry {day}"])

print("finished writing reports")
actual output (Python 3.14.4, run with the process's open-file limit lowered to 256 to trigger the failure quickly)
Traceback (most recent call last):
  File "/tmp/issue_26_unclosed_files.py", line 10, in <module>
  File "/tmp/issue_26_unclosed_files.py", line 4, in write_daily_report
OSError: [Errno 24] Too many open files: '/tmp/ch26_report_253.txt'

Note that this traceback doesn't show the usual source-line excerpt under each frame — with the file-descriptor limit already exhausted, Python can't open its own source file a second time to read that context line back out, so the frame headers appear without it. The file and line information is still exact.

On a real production server the default limit is much higher than 256, so this failure typically takes days or weeks of accumulation to surface — which is part of what makes file-handle leaks so easy to miss in testing and so disruptive in production.

Thought process: the fix isn't just "close the file" — it's recognizing that any resource acquired with an explicit "open" step (a file, a socket, a database connection, a lock) needs an equally explicit "close" step that runs even when something goes wrong in between, which is exactly what a with block guarantees and manual open/close calls don't.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function write_daily_report(day, lines) that writes each line to a file named report_{day}.txt. Use a "with" block so the file handle is guaranteed to be closed as soon as writing finishes, even if an exception is raised partway through. Explain why keeping open file handles in a long-lived list instead is a real production bug (OSError: Too many open files), not just a style preference.
#27

A mutable class attribute shared by every instance

Symptom

Two supposedly independent RequestLogger instances end up sharing the exact same history — and both keep growing even though only one of them is being actively used, because appending to either one appends to both.

Root cause

Chapter 14 covered the difference between a class attribute (defined directly in the class body, shared by every instance) and an instance attribute (assigned via self.x = ... in __init__, unique per instance). history = [] written at class level is a class attribute — there's exactly one list object, and every instance's self.history resolves to that same shared list unless an instance explicitly overrides it. This is the class-level cousin of the mutable-default-argument bug (issue #41 in Category 5).

Fix

Create the mutable list inside __init__ as an instance attribute — self.history = [] — so each instance gets its own fresh list instead of sharing one across the entire class.

issue_27_mutable_class_attr.py
class RequestLogger:
    history = []  # class attribute -- shared by every instance, not per-instance!

    def __init__(self, name):
        self.name = name

    def log(self, message):
        self.history.append(f"[{self.name}] {message}")

logger_a = RequestLogger("service-a")
logger_b = RequestLogger("service-b")

for i in range(1000):
    logger_a.log(f"request {i}")

for i in range(1000):
    logger_b.log(f"request {i}")

print(f"logger_a.history length: {len(logger_a.history)}")
print(f"logger_b.history length: {len(logger_b.history)}")
print(f"same list object: {logger_a.history is logger_b.history}")
actual output (Python 3.14.4)
logger_a.history length: 2000
logger_b.history length: 2000
same list object: True
#28

A "just in case" results list that never gets released

Symptom

A batch-processing worker's memory usage grows in a straight line with the total number of records it has ever processed, not the number in its current batch.

Root cause

Chapter 25 covered measuring what a program actually holds in memory at once. Here, every batch's rows are appended to all_rows_seen "in case a report needs to look back," and the running average is recomputed over the entire history on every batch — so both the memory and the work grow without bound, for a feature that's speculative at best.

Fix

Only keep what's actually needed going forward: a running total and count (two numbers) produce the same average without retaining a single row, or persist historical data somewhere with its own storage and retention policy instead of an in-memory Python list.

issue_28_dataframe_accumulation.py
import tracemalloc

def summarize_batch(all_rows_seen, new_rows):
    # keeps every row ever seen, "just in case a report needs to look back"
    all_rows_seen.extend(new_rows)
    return sum(row["amount"] for row in all_rows_seen) / len(all_rows_seen)

tracemalloc.start()

all_rows_seen = []
for batch_num in range(200):
    new_rows = [{"amount": 1} for _ in range(1000)]
    average = summarize_batch(all_rows_seen, new_rows)

current, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
print(f"rows retained across 200 batches: {len(all_rows_seen)}")
print(f"peak traced memory: {peak / 1_000_000:.1f} MB")
actual output (Python 3.14.4) -- your own numbers will vary by machine
rows retained across 200 batches: 200000
peak traced memory: 38.6 MB
#29

An lru_cache with no maxsize, on an input that's never repeated

Symptom

A thumbnail-rendering service that added caching "for speed" doesn't actually get faster in production — and its memory usage grows steadily instead, in direct proportion to the number of requests served.

Root cause

Chapter 25's caching guidance applies just as much to functools.lru_cache as to a hand-rolled dict: maxsize=None means unbounded. Caching only pays off when the same input recurs; here every image_id is a one-off (a fresh upload), so the cache never gets a hit — it just accumulates one new entry per request, forever, with zero benefit.

Fix

Set a concrete maxsize so the cache evicts old entries once full (issue #21's fix, applied via the standard library this time) — and more importantly, verify the access pattern actually has repeats before adding a cache at all. A cache on non-repeating input is pure memory overhead with no upside.

issue_29_lru_missing_bound.py
from functools import lru_cache

@lru_cache(maxsize=None)  # unbounded -- every distinct input is cached forever
def render_thumbnail(image_id, size):
    # stands in for genuinely expensive image processing
    return f"thumbnail-of-{image_id}-at-{size}px"

# simulate a service handling requests for many distinct, one-off image IDs
for i in range(50_000):
    render_thumbnail(f"user-upload-{i}", 128)

info = render_thumbnail.cache_info()
print(f"cache entries: {info.currsize}")
print(f"cache hits: {info.hits}, misses: {info.misses}")
actual output (Python 3.14.4)
cache entries: 50000
cache hits: 0, misses: 50000

Zero cache hits out of 50,000 calls is the tell: every single lookup was a miss, meaning the cache did no useful work at all — it only ever grew.

#30

A registry that keeps objects alive by design, unintentionally

Symptom

A session registry meant only to look up active sessions ends up being the reason sessions never get garbage collected, even long after every other part of the program has finished with them.

Root cause

A plain dict holds a strong reference to every value it contains — that's normal dict behavior, and usually exactly what's wanted. But a registry whose entire job is "let me look this up if it still exists" doesn't need to be the thing keeping it alive; here, every Session the caller creates and discards stays alive anyway, purely because the registry still references it.

Fix

Use weakref.WeakValueDictionary instead of a plain dict when a collection's purpose is tracking, not owning — entries disappear automatically the moment nothing else references the value, which is usually the actual intent of a "registry."

issue_30_weakref_fix_demo.py
import weakref

class Session:
    def __init__(self, session_id):
        self.session_id = session_id

class SessionRegistry:
    def __init__(self):
        self._sessions = {}  # plain dict -- holds a strong reference forever

    def register(self, session):
        self._sessions[session.session_id] = session

    def count(self):
        return len(self._sessions)

class SessionRegistryFixed:
    def __init__(self):
        self._sessions = weakref.WeakValueDictionary()  # doesn't keep sessions alive

    def register(self, session):
        self._sessions[session.session_id] = session

    def count(self):
        return len(self._sessions)

registry = SessionRegistry()
for i in range(1000):
    s = Session(i)
    registry.register(s)
    # caller drops its reference to s here -- but the registry keeps it alive anyway
print(f"leaky registry still holding: {registry.count()} sessions")

registry_fixed = SessionRegistryFixed()
for i in range(1000):
    s = Session(i)
    registry_fixed.register(s)
    # caller drops its reference; WeakValueDictionary lets it actually be collected
print(f"weakref-based registry holding: {registry_fixed.count()} sessions")
actual output (Python 3.14.4)
leaky registry still holding: 1000 sessions
weakref-based registry holding: 1 sessions

The weakref-based registry ends up holding just 1 session — the very last one, still referenced by the loop variable s at the moment count() runs. Every earlier session was already collected the instant its last strong reference went away.

Quick recap
  • A memory leak in Python almost always means "something is still reachable that shouldn't be" — not a language failure, but an object graph that keeps a path alive longer than intended.
  • Caches, registries, closures, and class attributes are the most common places an unbounded collection hides, because each one looks like ordinary, correct code in isolation.
  • weakref (issues #23 and #30) and bounded collections like collections.deque(maxlen=...) or lru_cache(maxsize=...) (issues #21, #25, #29) are the two main tools for turning "grows forever" into "grows up to a limit."
In the Real World (Category 3)
Category 4 of 8

4. Concurrency & Deadlocks

Chapter 20 introduced threading as a way to overlap I/O-bound work. This category is about what goes wrong once multiple threads touch the same data or the same locks — races that corrupt a shared value, and deadlocks that freeze a program entirely. A few of these repros need a little extra machinery (forcing thread switches, using daemon threads) purely to make timing-dependent bugs reproducible on the page; that machinery is called out where it's used.

#31

A race condition on a shared counter with no lock

Symptom

Eight threads each increment a shared counter by a known amount, but the final total comes out lower than the sum of what every thread should have contributed — and the exact shortfall changes from run to run.

Root cause

Chapter 20 covered starting and joining threads, but counter += 1 is not one atomic step — it's read counter, add 1, write the result back. If two threads both read the same value before either writes its update back, one thread's increment is silently lost. Python's GIL (Global Interpreter Lock) prevents two threads from running Python bytecode at the exact same instant, but it does not prevent a thread from being switched out in the middle of a multi-step operation like this one — which is exactly where the race lives.

Fix

Protect the read-modify-write with a threading.Lock (issue #40 below) so only one thread can execute that sequence at a time — turning three separate steps back into one effectively atomic one.

issue_31_race_condition.py
import threading
import time

counter = 0

def increment(times):
    global counter
    for _ in range(times):
        current = counter
        time.sleep(0)  # force a thread-switch opportunity between read and write
        counter = current + 1

threads = [threading.Thread(target=increment, args=(2000,)) for _ in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"expected: {8 * 2000}")
print(f"actual:   {counter}")
actual output (Python 3.14.4) -- the exact number lost to the race varies by run; this is a single real run, not a fixed number
expected: 16000
actual:   2002

The time.sleep(0) here exists purely to make this race reliably visible on the page — it forces Python to check for a thread switch right between the read and the write, widening a gap that's normally too narrow to hit often. Without it, this exact code would still be broken, just less predictably so — which is part of what makes races so dangerous: the bug is real even on runs where nothing looks wrong.

Thought process: "it worked when I tested it" is close to meaningless for concurrency bugs — a race condition can pass every test run and still be present, because whether it manifests depends on exact timing that testing doesn't control. The fix has to be reasoned about structurally (is this shared state ever mutated by more than one thread without a lock?), not verified by running the code a few times and seeing no error.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a thread-safe Counter class with an increment() method, using a threading.Lock so that many threads calling increment() concurrently never lose an update. Then write a short demonstration that starts 8 threads, each incrementing the same Counter instance 2000 times, joins them all, and prints the final value -- it must always equal exactly 16000, run after run, with no race condition.
#32

Deadlock from acquiring two locks in different orders

Symptom

Two threads that each transfer funds between two accounts — one A-to-B, one B-to-A — occasionally hang forever, with both threads stuck and neither making progress.

Root cause

transfer_a_to_b() acquires lock_a then lock_b; transfer_b_to_a() acquires lock_b then lock_a — the opposite order. If both threads grab their first lock at roughly the same time, each ends up waiting forever for the lock the other thread is holding. Neither thread can proceed, and neither will ever release what it's holding, since the release happens only after the wait — a classic deadlock.

Fix

Establish one global ordering for acquiring locks (e.g. always sort accounts by ID and lock the lower one first) and have every code path follow it — if both functions always acquired lock_a before lock_b, the deadlock in this exact shape becomes structurally impossible.

issue_32_deadlock_lock_order.py
import os
import sys
import threading
import time

lock_a = threading.Lock()
lock_b = threading.Lock()

def transfer_a_to_b():
    with lock_a:
        time.sleep(0.1)  # simulate some work, widening the window for the deadlock
        with lock_b:
            print("transferred A -> B")

def transfer_b_to_a():
    with lock_b:
        time.sleep(0.1)
        with lock_a:
            print("transferred B -> A")

t1 = threading.Thread(target=transfer_a_to_b, daemon=True)
t2 = threading.Thread(target=transfer_b_to_a, daemon=True)
t1.start()
t2.start()
t1.join(timeout=3)
t2.join(timeout=3)

print(f"t1 still alive (deadlocked): {t1.is_alive()}")
print(f"t2 still alive (deadlocked): {t2.is_alive()}")
sys.stdout.flush()
os._exit(1)  # both daemon threads are still holding a lock forever -- force process exit
actual output (Python 3.14.4)
t1 still alive (deadlocked): True
t2 still alive (deadlocked): True

daemon=True and the manual os._exit(1) at the end exist only so this demo terminates instead of hanging the page's build process forever — both threads really are stuck waiting on each other permanently. A real deadlocked process, without that escape hatch, would simply hang until something external (an operator, a health-check timeout) killed it.

#33

Threading a CPU-bound task and expecting a speedup

Symptom

Splitting a pure-computation task across two threads, expecting roughly a 2x speedup on a multi-core machine, produces no speedup at all — sometimes it's even slightly slower.

Root cause

Chapter 20 covered that CPython's GIL allows only one thread to execute Python bytecode at a time, no matter how many CPU cores are available. Threading genuinely helps when threads spend most of their time waiting (for a network response, for disk I/O) — the GIL is released during that wait. A tight pure-Python loop like count_down() never waits for anything; it's 100% CPU-bound Python bytecode, so the GIL keeps the two threads running one at a time, exactly as if they'd run sequentially (plus a bit of thread-switching overhead).

Fix

For CPU-bound work, use multiprocessing instead of threading — separate processes each get their own Python interpreter and their own GIL, so they genuinely run in parallel across cores. Reserve threading for I/O-bound work, where waiting (not computing) is most of what a thread does.

issue_33_gil_cpu_bound.py
import threading
import time

def count_down(n):
    while n > 0:
        n -= 1

N = 30_000_000

start = time.perf_counter()
count_down(N)
count_down(N)
single_threaded_time = time.perf_counter() - start

start = time.perf_counter()
t1 = threading.Thread(target=count_down, args=(N,))
t2 = threading.Thread(target=count_down, args=(N,))
t1.start(); t2.start()
t1.join(); t2.join()
two_threads_time = time.perf_counter() - start

print(f"single-threaded, sequential: {single_threaded_time:.3f}s")
print(f"two threads, 'parallel':     {two_threads_time:.3f}s")
actual output (Python 3.14.4) -- your own numbers will vary by machine
single-threaded, sequential: 2.164s
two threads, 'parallel':     2.182s

No speedup — if anything, a hair slower, purely from thread-management overhead. This is the single most common GIL misconception in practice: "more threads" isn't "more parallelism" for CPU-bound Python code, no matter how many cores the machine has.

#34

Forgetting to join a thread before reading its result

Symptom

A function that kicks off background work in threads and then immediately checks the results reports an empty list, even though the work clearly did finish (just a fraction of a second later).

Root cause

Chapter 20 covered thread.start() as non-blocking: it schedules the thread to run and returns immediately, without waiting for it to finish. run_batch_missing_join() starts three threads but never calls t.join() on any of them — so it returns before any of the threads have necessarily completed their time.sleep(0.3) plus computation, and results is still empty at that moment.

Fix

Call t.join() on every thread the function started before reading anything those threads were supposed to produce — join() blocks until that specific thread has actually finished, which is the whole point of it.

issue_34_missing_join.py
import threading
import time

results = []

def slow_computation(n):
    time.sleep(0.3)  # stands in for real work -- an API call, a file write, etc.
    results.append(n * n)

def run_batch_missing_join(values):
    threads = []
    for v in values:
        t = threading.Thread(target=slow_computation, args=(v,))
        t.start()
        threads.append(t)
    # BUG: no t.join() here -- the function returns before any thread finishes
    return "batch started"

print(run_batch_missing_join([1, 2, 3]))
print(f"results immediately after the function returns: {results}")
time.sleep(0.5)
print(f"results half a second later: {results}")
actual output (Python 3.14.4)
batch started
results immediately after the function returns: []
results half a second later: [1, 4, 9]
#35

A producer/consumer queue with no way to signal "done"

Symptom

A background consumer thread reads from a queue and processes everything correctly — and then the whole program hangs, never exiting, even though there's clearly nothing left to do.

Root cause

Chapter 20's threading model extends naturally to queue.Queue for producer/consumer patterns — but q.get() blocks by default when the queue is empty, waiting for the next item to arrive. The producer here puts three items and then simply stops, with no mechanism telling the consumer "that was the last one." The consumer's while True: q.get() is left waiting on a fourth item that will never come.

Fix

Have the producer put a sentinel value (like None) onto the queue once it's done, and have the consumer break its loop when it sees that sentinel — or use q.join()/task_done() together with a separate shutdown signal so the consumer knows precisely when to stop waiting.

issue_35_queue_producer_consumer.py
import queue
import threading

def producer(q, items):
    for item in items:
        q.put(item)
    # BUG: never puts a sentinel value or otherwise signals "no more items"

def consumer(q, results):
    while True:
        item = q.get()  # blocks forever once the queue is empty and never told to stop
        results.append(item * 2)
        q.task_done()

q = queue.Queue()
results = []

t_producer = threading.Thread(target=producer, args=(q, [1, 2, 3]), daemon=True)
t_consumer = threading.Thread(target=consumer, args=(q, results), daemon=True)
t_producer.start()
t_consumer.start()
t_producer.join(timeout=2)

q_drained = threading.Event()

def wait_for_queue():
    q.join()
    q_drained.set()

waiter = threading.Thread(target=wait_for_queue, daemon=True)
waiter.start()
waiter.join(timeout=1)

print(f"producer finished: {not t_producer.is_alive()}")
print(f"all 3 items processed within 1s: {q_drained.is_set()}")
print(f"results so far: {sorted(results)}")
print(f"consumer thread still blocked on q.get(), waiting for a 4th item: {t_consumer.is_alive()}")
actual output (Python 3.14.4)
producer finished: True
all 3 items processed within 1s: True
results so far: [2, 4, 6]
consumer thread still blocked on q.get(), waiting for a 4th item: True

All three items really were processed correctly — the queue drained, task_done() was called three times, and q.join() returned. The bug isn't in the processing at all; it's that the consumer thread itself never terminates, which in a real program without daemon threads would prevent the whole process from exiting.

#36

Check-then-act on a shared list from multiple threads

Symptom

A pool of worker threads pulling tasks off a shared list occasionally crashes with IndexError: pop from empty list, even though every worker explicitly checks while shared_queue: before popping.

Root cause

The check (if not shared_queue) and the act (shared_queue.pop()) are two separate steps, and nothing stops another thread from running its own pop in between them. Thread A can see a non-empty list, get interrupted, and by the time it actually calls .pop(), thread B has already emptied it — the check was true when made, but false by the time it's acted on.

Fix

Make the check-and-pop a single atomic operation instead of two separate steps — wrap both in the same with lock: block, or catch IndexError around the pop() and treat it as "someone else got there first" rather than a fatal error.

issue_36_thread_unsafe_list_mutation.py
import sys
import threading
import time

sys.setswitchinterval(0.0000001)

shared_queue = [f"task-{i}" for i in range(200)]
processed = []
errors = []

def worker():
    while True:
        if not shared_queue:  # check
            return
        time.sleep(0)  # force a thread-switch opportunity between check and act
        try:
            task = shared_queue.pop()  # act -- another thread may have emptied it by now
        except IndexError as e:
            errors.append(e)
            return
        processed.append(task)

threads = [threading.Thread(target=worker) for _ in range(16)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"tasks processed: {len(processed)}")
print(f"IndexError occurrences from the race: {len(errors)}")
if errors:
    print(f"example: {errors[0]!r}")
actual output (Python 3.14.4) -- exact count of races varies by run
tasks processed: 200
IndexError occurrences from the race: 13
example: IndexError('pop from empty list')

sys.setswitchinterval() and the time.sleep(0) are there purely to widen the timing window so the race reliably shows up in a short script — the underlying bug (check-then-act on shared mutable state) is exactly as real without them, just harder to trigger on demand.

#37

A plain Lock deadlocking against itself

Symptom

A function that acquires a lock, then calls a second function that also tries to acquire the very same lock, hangs forever — on the very first call, with no other threads involved at all.

Root cause

A plain threading.Lock doesn't track which thread holds it — once acquired, any further attempt to acquire it blocks, even from the exact same thread that's already holding it. outer() acquires lock, then calls inner(), which tries to acquire the same lock again from within the same thread — and blocks waiting for itself to release something it's currently holding.

Fix

Use threading.RLock (a re-entrant lock) when the same thread legitimately needs to acquire the same lock more than once, such as one locked method calling another — an RLock tracks the owning thread and lets it re-acquire without blocking on itself.

issue_37_lock_not_reentrant.py
import threading

lock = threading.Lock()

def outer():
    with lock:
        inner()  # tries to acquire the SAME plain Lock again -- deadlocks immediately

def inner():
    with lock:
        print("inner acquired the lock")

t = threading.Thread(target=outer, daemon=True)
t.start()
t.join(timeout=2)
print(f"thread still blocked (self-deadlocked): {t.is_alive()}")
actual output (Python 3.14.4)
thread still blocked (self-deadlocked): True

Switching lock = threading.Lock() to lock = threading.RLock() is the entire fix — with that one change, outer() prints "inner acquired the lock" and the thread finishes normally instead of hanging.

#38

An exception raised inside a worker thread that's never surfaced

Symptom

A batch of tasks submitted to a thread pool includes one that fails, but the program prints its normal "all done" message and continues on as if every task had succeeded.

Root cause

A concurrent.futures.Future captures an exception raised inside its worker function rather than letting it propagate immediately — it's stored on the Future object, waiting to be re-raised the moment someone calls .result(). If nothing ever calls .result() on a given future, that captured exception is simply never looked at again.

Fix

Always call .result() on every Future a pool produces (or iterate with concurrent.futures.as_completed() and call .result() on each) so any exception a worker raised gets re-raised where it can actually be seen and handled.

issue_38_threadpool_exception_swallowed.py
from concurrent.futures import ThreadPoolExecutor

def risky_task(n):
    if n == 3:
        raise ValueError(f"bad input: {n}")
    return n * n

with ThreadPoolExecutor(max_workers=4) as pool:
    futures = [pool.submit(risky_task, n) for n in range(5)]
    # BUG: results are never actually read with .result(), so exceptions
    # raised inside the worker threads are captured but never surfaced
    print("all tasks submitted, pool shutting down")

print("program continues as if everything succeeded")
actual output (Python 3.14.4)
all tasks submitted, pool shutting down
program continues as if everything succeeded

Adding results = [f.result() for f in futures] right after submitting is the fix — and it changes the output completely, because .result() re-raises the worker's real exception:

actual output after adding .result() (Python 3.14.4)
Traceback (most recent call last):
  File "issue_38_threadpool_exception_fixed.py", line 10, in <module>
    results = [f.result() for f in futures]  # .result() re-raises the worker's exception here
               ~~~~~~~~^^
  File "/usr/lib/python3.14/concurrent/futures/_base.py", line 450, in result
    return self.__get_result()
           ~~~~~~~~~~~~~~~~~^^
  File "/usr/lib/python3.14/concurrent/futures/_base.py", line 395, in __get_result
    raise self._exception
  File "/usr/lib/python3.14/concurrent/futures/thread.py", line 86, in run
    result = ctx.run(self.task)
  File "/usr/lib/python3.14/concurrent/futures/thread.py", line 73, in run
    return fn(*args, **kwargs)
  File "issue_38_threadpool_exception_fixed.py", line 5, in risky_task
    raise ValueError(f"bad input: {n}")
ValueError: bad input: 3
#39

Iterating a dict in one thread while another thread mutates it

Symptom

A "count active sessions" report, run periodically in a background thread, occasionally crashes outright with a RuntimeError instead of just returning a slightly-stale count.

Root cause

Chapter 8 covered that mutating a dict's size while iterating it is unsafe — that rule doesn't go away just because the mutation happens on a different thread. While report_active_sessions() iterates sessions.items(), expire_old_sessions() deletes keys from the very same dict on another thread; Python detects the dict's size changed mid-iteration and raises, rather than silently producing a wrong count.

Fix

Protect the shared dict with a threading.Lock that both the reader and the writer acquire, or take a snapshot (list(sessions.items())) while holding the lock briefly, then release the lock and iterate the snapshot instead of the live dict.

issue_39_dict_mutation_during_iteration_threads.py
import threading
import time

sessions = {f"session-{i}": {"active": True} for i in range(500)}

def expire_old_sessions():
    time.sleep(0.01)
    for key in list(sessions.keys())[:100]:
        del sessions[key]

def report_active_sessions():
    count = 0
    for key, value in sessions.items():  # BUG: iterating while another thread mutates the dict
        time.sleep(0.0001)
        if value["active"]:
            count += 1
    return count

t_expire = threading.Thread(target=expire_old_sessions)
t_report = threading.Thread(target=report_active_sessions)
t_expire.start()
t_report.start()
t_expire.join()
t_report.join()
print("both threads finished without the loop crashing this time")
actual output (Python 3.14.4)
Exception in thread Thread-2 (report_active_sessions):
Traceback (most recent call last):
  File "/usr/lib/python3.14/threading.py", line 1082, in _bootstrap_inner
    self._context.run(self.run)
    ~~~~~~~~~~~~~~~~~^^^^^^^^^^
  File "/usr/lib/python3.14/threading.py", line 1024, in run
    self._target(*self._args, **self._kwargs)
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "issue_39_dict_mutation_during_iteration_threads.py", line 13, in report_active_sessions
    for key, value in sessions.items():  # BUG: iterating while another thread mutates the dict
                      ~~~~~~~~~~~~~~^^
RuntimeError: dictionary changed size during iteration
both threads finished without the loop crashing this time

Notice this crash didn't stop the program — an unhandled exception inside a non-daemon thread prints its traceback to stderr and kills that thread, but the main thread and the other thread carry on, which is exactly why this bug can go unnoticed for a long time: nothing about the overall process looks like it failed.

Thought process: this is the same underlying rule as Chapter 8's "don't mutate a dict while iterating it," just harder to spot because the mutation isn't in the visible call stack — it's happening concurrently, on a different thread, somewhere else in the codebase entirely. Recognizing "this dict is touched from more than one thread" as a red flag, independent of whether any single function looks unsafe on its own, is the actual skill here.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a thread-safe SessionStore class wrapping a dict of sessions, with expire_old(keys) and count_active() methods that can both be called concurrently from different threads without ever raising "dictionary changed size during iteration." Use a threading.Lock to protect every read and write of the underlying dict, and have count_active() take a snapshot of the data while holding the lock rather than iterating the live dict.
#40

Fixing issue #31 with a lock

Symptom

N/A — this entry shows the fix for issue #31's race condition, run the same way, to confirm the lock actually closes the gap rather than just making the race less frequent.

Root cause

Issue #31's counter += 1 was unsafe specifically because it's three separate steps that another thread can interleave with. Wrapping those same three steps in with lock: means only one thread can be inside that block at any moment — any other thread calling increment_safe() simply waits at the with lock: line until the current holder finishes and releases it.

Fix

This is the fix — a threading.Lock acquired around the entire read-modify-write sequence, released automatically (even on an exception) by the with statement, matching Chapter 12's with-block cleanup guarantee.

issue_40_lock_fixes_race.py
import threading

counter = 0
lock = threading.Lock()

def increment_safe(times):
    global counter
    for _ in range(times):
        with lock:  # only one thread at a time can read-modify-write counter
            current = counter
            current = current + 1
            counter = current

threads = [threading.Thread(target=increment_safe, args=(2000,)) for _ in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()

print(f"expected: {8 * 2000}")
print(f"actual:   {counter}")
actual output (Python 3.14.4, run repeatedly -- always exact, unlike issue #31)
expected: 16000
actual:   16000

Unlike issue #31, this version produces exactly 16000 every single time it's run, no matter how many times — that consistency, not just one lucky correct run, is what actually proves a concurrency fix works.

Quick recap
  • The GIL prevents two threads from running Python bytecode simultaneously, but it does not make multi-step operations (x += 1, check-then-act, iterate-while-mutating) atomic — races are still very real in pure Python code.
  • Deadlocks (issues #32, #37) come from lock-acquisition order or re-entrancy, not from randomness — they're deterministic bugs that happen to depend on timing to trigger.
  • Threading speeds up I/O-bound work (waiting on a network, a disk, a queue) but not CPU-bound work (issue #33) — for CPU-bound parallelism, multiprocessing is the right tool, not more threads.
In the Real World (Category 4)
Category 5 of 8

5. Data Corruption

These bugs are the most dangerous kind in this whole chapter, precisely because most of them don't crash anything. The program runs, returns a value, and looks completely fine — the damage is a wrong answer that quietly ends up in a database, a report, or a customer-facing number, sometimes for a long time before anyone notices.

#41

The mutable default argument trap

Symptom

A "start a new shopping cart" function occasionally hands a customer a cart that already has someone else's items in it, with no code anywhere that looks like it should share carts between customers.

Root cause

Chapter 10 covered default argument values — what it's easy to miss is that a default value is evaluated exactly once, when the def statement runs, not fresh on every call. cart=[] creates one single list object at function-definition time; every call that doesn't pass its own cart argument gets that same object, and any mutation (like .append()) persists onto the next such call.

Fix

Use cart=None as the default, and create a fresh list inside the function body when cart is None — def add_item(item, cart=None): cart = [] if cart is None else cart. This is one of the most well-known Python gotchas precisely because the code reads as obviously correct until you know to look for it.

issue_41_mutable_default_arg.py
def add_item(item, cart=[]):  # BUG: default list is created ONCE, at def time, and reused
    cart.append(item)
    return cart

cart_a = add_item("apple")
print(f"cart_a: {cart_a}")

cart_b = add_item("banana")  # a brand-new customer's cart -- should start empty
print(f"cart_b: {cart_b}")

print(f"same list object: {cart_a is cart_b}")
actual output (Python 3.14.4)
cart_a: ['apple']
cart_b: ['apple', 'banana']
same list object: True

Thought process: this bug is so well-known that an AI assistant will very likely avoid it if asked directly — but that's exactly why it's worth testing: does the assistant explain why cart=None is needed, or just pattern-match to the "safe" version without understanding when a mutable default is actually dangerous (versus, say, a default of an immutable tuple, which is perfectly fine to share)?

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function add_item(item, cart=None) that appends item to cart and returns it, creating a brand-new empty list when cart isn't provided. Explain specifically why "def add_item(item, cart=[]):" is a bug -- what actually happens across multiple calls -- not just that it's "considered bad practice."
#42

Shallow copy vs. deep copy

Symptom

Making a copy of an order to modify independently ("just change the status, don't touch the original") ends up silently modifying the original order too — but only its list-valued fields, not its plain string fields.

Root cause

Chapter 8 and Chapter 15 covered dict.copy() as a shallow copy: it creates a new dict, but each value inside it is the same object as in the original, not a new copy of that value. Reassigning a key (order_a["status"] = "shipped") only affects the new dict, because that replaces which object the key points to. But mutating a shared nested object in place (order_a["items"].append(...)) changes the one list both dicts are still pointing at.

Fix

Use copy.deepcopy() when a copy needs to be fully independent, including everything nested inside it — it recursively copies every mutable value, not just the top-level container, so mutating the copy never touches the original.

issue_42_shallow_copy.py
import copy

order_template = {"items": ["notebook"], "status": "pending"}

order_a = order_template.copy()  # BUG: shallow copy -- "items" list is still shared
order_a["status"] = "shipped"      # this is fine, strings are immutable
order_a["items"].append("pen")     # this mutates the SAME list as order_template's

print(f"order_template: {order_template}")
print(f"order_a:        {order_a}")

order_b = copy.deepcopy(order_template)
order_b["items"].append("eraser")
print(f"order_template after deepcopy mutation: {order_template}")
print(f"order_b:                                 {order_b}")
actual output (Python 3.14.4)
order_template: {'items': ['notebook', 'pen'], 'status': 'pending'}
order_a:        {'items': ['notebook', 'pen'], 'status': 'shipped'}
order_template after deepcopy mutation: {'items': ['notebook', 'pen'], 'status': 'pending'}
order_b:                                 {'items': ['notebook', 'pen', 'eraser'], 'status': 'pending'}

Note that order_template's items already shows 'pen' from the shallow-copy mutation earlier — the deepcopy in the second half correctly stays independent from that point forward, adding 'eraser' only to order_b.

#43

Comparing floating-point numbers with ==

Symptom

An account reconciliation check flags a balance as "not fully funded" even though, by every human reading of the numbers involved, it clearly should be exactly $1.00.

Root cause

Chapter 2 introduced floats; what it's easy to gloss over is that most decimal fractions (including something as simple as 0.1) can't be represented exactly in binary floating point — the same way 1/3 can't be written exactly in decimal. Each addition accumulates a tiny rounding error, and after ten additions, the result is off from 1.0 by a sliver too small to see when printed casually, but large enough that == reports False.

Fix

Never compare floats for exact equality when they result from arithmetic — use math.isclose(a, b) for a tolerance-based comparison, or use decimal.Decimal instead of float entirely for money, where exact decimal representation actually matters.

issue_43_float_equality.py
account_balance = 0.0
for _ in range(10):
    account_balance += 0.1  # each addition accumulates tiny binary floating-point error

print(f"balance after adding 0.1 ten times: {account_balance}")
print(f"is it exactly equal to 1.0? {account_balance == 1.0}")

if account_balance == 1.0:
    print("account fully funded")
else:
    print("account NOT fully funded -- reconciliation flags a false discrepancy")
actual output (Python 3.14.4)
balance after adding 0.1 ten times: 0.9999999999999999
is it exactly equal to 1.0? False
account NOT fully funded -- reconciliation flags a false discrepancy
#44

Silent truncation when coercing types

Symptom

An inventory system that's supposed to track whole units ends up losing small fractional amounts on every single item that arrives with a fractional quantity — no error is ever raised.

Root cause

Chapter 2 covered int() as a way to convert to an integer — what it didn't stress is that int() truncates toward zero rather than rounding, and does so completely silently. int(float("4.9")) doesn't round to 5; it discards everything after the decimal point and returns 4, with nothing in the output to suggest data was thrown away.

Fix

Decide deliberately what fractional quantities should mean before converting — round() if the nearest whole number is correct, an explicit validation error if fractional units should never be allowed at all, or keep the value as a float/Decimal if fractions are actually meaningful data, rather than letting int() make that decision implicitly.

issue_44_silent_truncation.py
def parse_quantity(raw_value):
    return int(float(raw_value))  # BUG: truncates toward zero instead of rounding or rejecting

# a form field that should represent whole units, but a user (or a bad
# upstream calculation) supplied a fractional value
raw_inputs = ["4.9", "3.1", "-2.9"]
quantities = [parse_quantity(v) for v in raw_inputs]

print(f"raw inputs:  {raw_inputs}")
print(f"parsed as:   {quantities}")
print("4.9 units of inventory silently became 4 -- no error, no warning")
actual output (Python 3.14.4)
raw inputs:  ['4.9', '3.1', '-2.9']
parsed as:   [4, 3, -2]
4.9 units of inventory silently became 4 -- no error, no warning

Notice -2.9 became -2, not -3 — "truncate toward zero" means int() always moves toward 0, regardless of sign, which is a different rule than "always round down" and easy to get backwards when reasoning about negative values.

#45

A CSV file saved in the wrong encoding

Symptom

Reading a CSV file of customer names, exported from a Windows tool, crashes with a UnicodeDecodeError the instant a name contains an accented character.

Root cause

Chapter 13 covered reading files with open(), defaulting (on most platforms) to UTF-8. Many Windows tools instead save text as cp1252 (Windows-1252), which encodes accented characters using different byte sequences than UTF-8 does. Opening a cp1252 file while assuming UTF-8 means the decoder eventually hits a byte sequence that isn't valid UTF-8 and has no way to guess what it was actually supposed to mean.

Fix

Know (or detect) the actual encoding of files coming from outside your own system, and pass it explicitly: open(path, encoding="cp1252"). When the true encoding is genuinely unknown, a library like chardet can guess from the byte patterns, but "just assume UTF-8" silently breaks the moment that assumption is wrong.

issue_45_csv_encoding.py
import csv

# a CSV file saved by a Windows tool as Windows-1252, containing a customer name with an accent
with open("customers.csv", "wb") as f:
    f.write("name,city\r\n".encode("utf-8"))
    f.write("Jos\xe9 Garc\xeda,S\xe3o Paulo\r\n".encode("cp1252"))

def read_customers(path):
    with open(path, encoding="utf-8") as f:  # BUG: assumes UTF-8, file is actually cp1252
        return list(csv.DictReader(f))

read_customers("customers.csv")
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_45_csv_encoding.py", line 12, in <module>
    read_customers("customers.csv")
    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
  File "issue_45_csv_encoding.py", line 10, in read_customers
    return list(csv.DictReader(f))
  File "/usr/lib/python3.14/csv.py", line 176, in __next__
    self.fieldnames
  File "/usr/lib/python3.14/csv.py", line 163, in fieldnames
    self._fieldnames = next(self.reader)
                       ~~~~^^^^^^^^^^^^^
  File "<frozen codecs>", line 325, in decode
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe9 in position 14: invalid continuation byte
#46

An off-by-one error in pagination that silently drops records

Symptom

A paginated export of 25 records, fetched page by page, comes back missing the first 10 records entirely — with no error, and every individual page request "succeeding."

Root cause

Chapter 6 and Chapter 7 covered slicing as zero-based — records[0:10] is the first ten items. This API's page_number is 1-based (page 1 is the first page, matching how a human thinks about it), but the slicing math treats it as if it were already 0-based: start = page_number * page_size computes 1 * 10 = 10 for "page 1," which is actually where the second page of results starts.

Fix

Convert the 1-based page number to a 0-based offset explicitly before slicing: start = (page_number - 1) * page_size. Writing a quick unit test for "page 1 includes the very first record" would have caught this immediately — it's exactly the kind of boundary case Chapter 12-adjacent testing habits are meant to cover.

issue_46_pagination_off_by_one.py
records = list(range(1, 26))  # 25 records total, IDs 1-25

def get_page_slow(records, page_number, page_size):
    # BUG: page_number is 1-based from the API, but slicing needs a 0-based start
    start = page_number * page_size  # should be (page_number - 1) * page_size
    end = start + page_size
    return records[start:end]

page1 = get_page_slow(records, 1, 10)
page2 = get_page_slow(records, 2, 10)
page3 = get_page_slow(records, 3, 10)

print(f"page 1: {page1}")
print(f"page 2: {page2}")
print(f"page 3: {page3}")
all_returned = set(page1) | set(page2) | set(page3)
print(f"records 1-10 ever returned to the client: {sorted(all_returned & set(range(1, 11)))}")
actual output (Python 3.14.4)
page 1: [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
page 2: [21, 22, 23, 24, 25]
page 3: []
records 1-10 ever returned to the client: []

Every one of the first ten records — nearly half the dataset — is never returned on any page, and nothing about the response for page 1, 2, or 3 individually looks wrong. This is exactly the shape of bug that survives into production: each piece works; the composition silently loses data.

#47

Assuming dict key order matches a specific column order

Symptom

A CSV export built by joining a dict's .values() together produces rows where the columns are in a different order depending on which code path constructed each record — even though every record has the exact same fields.

Root cause

Chapter 8 covered that modern Python dicts preserve insertion order — a real, documented guarantee since Python 3.7. The bug here isn't that the guarantee is false; it's relying on it for something it was never meant to guarantee: which order a dict's keys end up in depends entirely on the order they were first assigned, which can differ between two code paths that build "the same" record from different sources.

Fix

Never rely on a dict's insertion order to imply a fixed column layout — explicitly list the field order once (e.g. a tuple of column names) and build every row by looking up each field from that fixed list: [record[field] for field in COLUMN_ORDER], so all rows are aligned regardless of how each record was originally built.

issue_47_dict_ordering_assumption.py
def build_csv_row(record):
    # BUG: assumes dict keys always come out in this exact order --
    # true in modern Python by insertion order, but the record's keys
    # depend on which fields the caller happened to set, in what order
    return ",".join(str(v) for v in record.values())

record_a = {"name": "Ana", "age": 30, "city": "Lima"}
record_b = {"age": 30, "name": "Ana", "city": "Lima"}  # same data, different insertion order

print(f"row from record_a: {build_csv_row(record_a)}")
print(f"row from record_b: {build_csv_row(record_b)}")
print("same logical record, but the CSV columns are now misaligned between rows")
actual output (Python 3.14.4)
row from record_a: Ana,30,Lima
row from record_b: 30,Ana,Lima
same logical record, but the CSV columns are now misaligned between rows
#48

Two visually identical strings that aren't equal

Symptom

A user's account lookup by name fails intermittently — the name displayed on screen looks exactly right, character for character, but == against the stored value returns False.

Root cause

Chapter 6 covered strings as sequences of characters, but some accented characters can be represented two different ways in Unicode: as one single "precomposed" code point, or as a plain letter followed by a separate combining accent mark. Both render identically on screen, but they are different sequences of code points — different lengths, even — so Python's == correctly reports them as unequal strings.

Fix

Normalize any text that crosses a system boundary (typed by a user, read from a file, received from an API) to one consistent Unicode form — typically NFC — using unicodedata.normalize("NFC", text), before comparing it or storing it as a lookup key.

issue_48_unicode_normalization.py
import unicodedata

# two different byte sequences that render identically on screen --
# one is "e" + a combining acute accent (U+0065 U+0301), the other is
# a single precomposed "e-with-acute" character (U+00E9)
name_decomposed = "Caf" + "e" + "́"
name_precomposed = "Café"

print(f"decomposed form: {name_decomposed!r} ({len(name_decomposed)} chars)")
print(f"precomposed form: {name_precomposed!r} ({len(name_precomposed)} chars)")
print(f"do they print the same? {name_decomposed} == {name_precomposed}")
print(f"are they equal as strings? {name_decomposed == name_precomposed}")

registered_users = {name_precomposed: "user-001"}
print(f"lookup with the decomposed form found the account? {name_decomposed in registered_users}")

# the fix: normalize both sides to the same form (e.g. NFC) before comparing/storing
normalized_a = unicodedata.normalize("NFC", name_decomposed)
normalized_b = unicodedata.normalize("NFC", name_precomposed)
print(f"after NFC normalization, equal? {normalized_a == normalized_b}")
actual output (Python 3.14.4)
decomposed form: 'Café' (5 chars)
precomposed form: 'Café' (4 chars)
do they print the same? Café == Café
are they equal as strings? False
lookup with the decomposed form found the account? False
after NFC normalization, equal? True

The two printed lines above look byte-for-byte identical in a rendered browser or terminal — that's the entire point. The len() difference (5 characters vs. 4) is the only clue visible without inspecting the actual Unicode code points.

#49

Silent wraparound when packing a value into a fixed-width field

Symptom

A daily event counter, serialized into a fixed-width field for a wire protocol, reports a wildly wrong (and much smaller) number on unusually busy days, while working perfectly on normal days.

Root cause

Chapter 3 covered bitwise operators including &. Masking a value with & 0xFFFFFFFF keeps only its lowest 32 bits — for any value that already fits in 32 bits, this is a no-op. But for a value that exceeds 2³² - 1 (4,294,967,295), the higher bits are silently discarded, producing a completely different, smaller number with no error or warning of any kind — unlike issue #4's TypeError, this is a valid Python int operation the whole way through.

Fix

Validate the value's range before masking or packing it into a fixed-width field, and raise an explicit error (or widen the field) when it doesn't fit — Python's own integers have no size limit, so this kind of overflow only happens at a boundary you construct yourself, and only that boundary can catch it.

issue_49_int_overflow_boundary.py
def encode_as_32bit_counter(count):
    # BUG: masking to 32 bits to match a fixed-width wire format, without
    # checking first whether the value actually fits -- this SILENTLY
    # wraps around instead of raising anything
    return count & 0xFFFFFFFF

total_events_today = 4_000_000_000       # fits comfortably in 32 bits
total_events_this_month = 4_300_000_000  # does NOT fit -- exceeds 2**32 - 1

encoded_today = encode_as_32bit_counter(total_events_today)
encoded_month = encode_as_32bit_counter(total_events_this_month)

print(f"today's true count:  {total_events_today}")
print(f"today's encoded:     {encoded_today}  (correct)")
print(f"month's true count:  {total_events_this_month}")
print(f"month's encoded:     {encoded_month}  (WRONG -- silently wrapped around)")
actual output (Python 3.14.4)
today's true count:  4000000000
today's encoded:     4000000000  (correct)
month's true count:  4300000000
month's encoded:     5032704  (WRONG -- silently wrapped around)
#50

Truncating by character count when the limit is actually in bytes

Symptom

A username that fits comfortably under a database column's stated character limit still fails to insert, with the database complaining the value is too long for the column.

Root cause

Chapter 6 covered len() on a string as the number of characters. Many database column types (a fixed-width VARBINARY, or VARCHAR under certain encodings) actually enforce a limit in bytes, not characters. Once text is encoded to UTF-8, characters outside the basic ASCII range take up 2, 3, or 4 bytes each — so a 10-character string can easily be 12+ bytes, silently exceeding a byte-based limit that a character-based truncation never accounted for.

Fix

Know which unit a given limit is actually measured in, and truncate accordingly — for a byte limit, encode first, truncate the bytes (carefully, so as not to split a multi-byte character in half), then decode back, rather than truncating the original string by character count and hoping it happens to fit.

issue_50_str_bytes_boundary.py
def truncate_username(name, max_bytes):
    # BUG: truncates by character count, but the storage limit is actually
    # a BYTE limit (e.g. a fixed-width database column) -- multi-byte
    # characters make this silently wrong
    return name[:max_bytes]

username = "Zoë_Müller99"  # contains multi-byte UTF-8 characters (ë, ü)
truncated = truncate_username(username, 10)
truncated_bytes = truncated.encode("utf-8")

print(f"original: {username!r} ({len(username)} chars, {len(username.encode('utf-8'))} bytes)")
print(f"'truncated to 10': {truncated!r} ({len(truncated)} chars, {len(truncated_bytes)} bytes)")
print(f"fits in a 10-byte column? {len(truncated_bytes) <= 10}")
actual output (Python 3.14.4)
original: 'Zoë_Müller99' (12 chars, 14 bytes)
'truncated to 10': 'Zoë_Müller' (10 chars, 12 bytes)
fits in a 10-byte column? False

"Truncated to 10 characters" produced a string that's still 12 bytes — two bytes over the actual limit — purely because two of its characters (ë and ü) each cost 2 bytes in UTF-8 instead of 1.

Quick recap
  • Most data corruption bugs never raise an exception — the program runs, returns something plausible, and the only sign anything is wrong is that the value itself is incorrect.
  • Boundary math (off-by-one pagination, byte-vs-character limits, fixed-width overflow) is a recurring source of silent corruption precisely because each individual number involved looks reasonable in isolation.
  • Text encoding (issues #45, #48, #50) is a common, underestimated source of production bugs the moment real-world names, addresses, or free text enter a system that assumed plain ASCII.
In the Real World (Category 5)
Category 6 of 8

6. Deployment & Environment

Every bug so far in this chapter can be reproduced by just running the code. This category is different: these bugs only exist because of a difference between where code was written and tested, and where it actually runs — a different Python version, a different working directory, a variable that's set on one machine and not another.

#51

Using a language feature newer than production's Python version

Symptom

Code that works perfectly on a developer's machine fails to even start on the production server, with a SyntaxError or ModuleNotFoundError raised the instant the file is loaded — before any of the actual logic runs.

Root cause

Python's standard library and syntax both grow over time — structural pattern matching (match/case) arrived in 3.10; tomllib became part of the standard library only in 3.11. Code written and tested on a developer's up-to-date local Python has no way to know that a production server, provisioned from an older base image, is running a version from before that feature existed.

Fix

Pin the exact Python version in a .python-version file (or the container base image tag) and match it across every environment — local, CI, and production — so "works on my machine" and "works in production" are testing the same interpreter, not just the same source code.

issue_51_python_version_mismatch.py
import sys

def load_config(path):
    import tomllib  # standard library only since Python 3.11 -- ImportError on older versions
    with open(path, "rb") as f:
        return tomllib.load(f)

print(f"running on Python {sys.version_info.major}.{sys.version_info.minor}")
print(f"tomllib available: {sys.version_info >= (3, 11)}")

# a developer wrote and tested this on their local Python 3.12 machine.
# the production server, provisioned from an older base image, runs Python 3.9 --
# `import tomllib` there raises ModuleNotFoundError, since tomllib didn't exist
# in the standard library until 3.11 (before that, the third-party "toml" package
# was needed, under a different import name and slightly different API)
actual output (Python 3.14.4)
running on Python 3.14
tomllib available: True

This exact file runs cleanly here, on 3.14 — that's the whole point of the bug. The failure is invisible in local development and only exists on whichever machine actually has an older interpreter, which is exactly why version pinning has to be enforced as infrastructure, not remembered as a habit.

#52

An unpinned dependency in requirements.txt

Symptom

A deployment that ran fine yesterday breaks today, with no code changes at all — the only thing that happened between deploys was a fresh pip install.

Root cause

Chapter 11 covered installing packages, but a requirements.txt line like requests (no version specified) doesn't mean "the version I tested with" — it means "whatever the newest compatible version is, at the exact moment pip install runs." A library's new release, even a routine one, can change default behavior, deprecate something the code relies on, or pull in its own updated (and possibly incompatible) sub-dependencies.

Fix

Pin exact versions (requests==2.31.0) or use a lockfile-based tool (pip-tools, poetry, uv) that records the exact resolved version of every dependency, direct and transitive, so every install — local, CI, or production — gets identical package versions.

issue_52_missing_dependency_pin.py
import importlib.metadata

def get_installed_version(package_name):
    try:
        return importlib.metadata.version(package_name)
    except importlib.metadata.PackageNotFoundError:
        return None

# what a loose requirements.txt entry like "requests" (no version pin) can lead to:
# dev installed requests 2.31 months ago; prod's fresh `pip install` today pulls
# whatever the latest is, which may have behavior or dependency changes
installed = get_installed_version("pip")  # using pip itself as a stand-in package to check
print(f"installed pip version right now: {installed}")
print("an unpinned 'pip' in requirements.txt would resolve to whatever is newest")
print("at install time -- not necessarily the version development was tested against")
actual output (Python 3.14.4) -- the exact version printed will vary by machine and by when this is run
installed pip version right now: 25.1.1
an unpinned 'pip' in requirements.txt would resolve to whatever is newest
at install time -- not necessarily the version development was tested against
#53

An environment variable that's set locally but not in production

Symptom

A service crashes immediately on startup in a freshly deployed container, with a KeyError pointing at an environment variable name — the same code has run without incident on every developer's machine for months.

Root cause

This is issue #1's KeyError pattern, but the missing key lives in os.environ instead of a plain dict. A developer's shell profile or a local .env file quietly exports variables like PAYMENT_API_KEY every time a terminal opens — a freshly provisioned production container has no such setup unless someone explicitly configured that variable in the deployment platform.

Fix

Validate all required environment variables at startup, before the service accepts any traffic, and fail with a clear message naming exactly which variable is missing (echoing issue #1's fix) — that turns a runtime KeyError deep in request-handling code into an immediate, unambiguous deployment failure.

issue_53_env_var_not_set.py
import os

def get_api_key():
    return os.environ["PAYMENT_API_KEY"]  # BUG: assumes it's always set

# works fine on the developer's machine, where a .env file or shell profile
# exports PAYMENT_API_KEY -- but a fresh production container, deployed
# without that variable configured in its environment, has no such key
if "PAYMENT_API_KEY" in os.environ:
    del os.environ["PAYMENT_API_KEY"]  # simulate the missing-in-prod case

get_api_key()
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_53_env_var_not_set.py", line 12, in <module>
    get_api_key()
    ~~~~~~~~~~~^^
  File "issue_53_env_var_not_set.py", line 4, in get_api_key
    return os.environ["PAYMENT_API_KEY"]  # BUG: assumes it's always set
           ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
  File "<frozen os>", line 709, in __getitem__
KeyError: 'PAYMENT_API_KEY'

Thought process: the interesting design decision isn't "check for the env var" — it's when to check. Checking lazily, the first time get_api_key() is called, means the failure surfaces mid-request, potentially minutes or hours after a bad deploy. Checking eagerly at startup means the failure surfaces immediately, before the service ever accepts traffic, which is almost always the better trade.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function check_required_env_vars(names) that checks os.environ for every variable name in the given list, and raises a single RuntimeError listing ALL missing variables at once (not just the first one found) if any are absent. Show how this would be called once at application startup, before the app starts accepting any requests, so a missing environment variable fails the deploy immediately and loudly instead of surfacing later as a random KeyError mid-request.
#54

A relative file path that assumes a specific working directory

Symptom

A function that loads a template file works every time it's run the "normal" way (cd into the project, then run the script) but fails with FileNotFoundError when launched by a process manager, a cron job, or a systemd service.

Root cause

Chapter 13 covered open() with a relative path — what's easy to miss is that a relative path is resolved against the process's current working directory, not against the location of the script file itself. A developer's habit of always running python app.py from inside the project folder makes the working directory always happen to line up; a systemd unit or cron job has no such habit and typically defaults to a different directory entirely (often / or the user's home directory).

Fix

Build paths relative to the script's own location using pathlib.Path(__file__).resolve().parent, rather than relying on whatever the current working directory happens to be at launch — that makes the code's file access independent of how or from where it's started.

issue_54_relative_path_cwd.py
import os

def load_template():
    # BUG: relative path assumes the process's current working directory
    # is always the project root -- true when run as `python app.py` from
    # the project folder, false when run as a systemd service, a cron job,
    # or from any other working directory
    with open("templates/welcome.txt") as f:
        return f.read()

os.makedirs("templates", exist_ok=True)
with open("templates/welcome.txt", "w") as f:
    f.write("Welcome!")

print("works when cwd is the project root:", load_template())

os.chdir("/tmp")  # simulate being launched from a different directory (e.g. by cron/systemd)
load_template()
actual output (Python 3.14.4)
works when cwd is the project root: Welcome!
Traceback (most recent call last):
  File "issue_54_relative_path_cwd.py", line 18, in <module>
    load_template()
    ~~~~~~~~~~~~~^^
  File "issue_54_relative_path_cwd.py", line 8, in load_template
    with open("templates/welcome.txt") as f:
         ~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: 'templates/welcome.txt'
#55

A naive datetime that means a different moment depending on timezone

Symptom

A report scheduled to run "at 9am" fires at 9am on a developer's laptop during testing, but fires at a completely different real-world time once deployed to a production server.

Root cause

datetime(2026, 7, 9, 9, 0, 0) with no timezone attached is a naive datetime — it represents "9 o'clock" without saying 9 o'clock where. A developer's laptop, set to their local timezone, and a production server, very often configured for UTC, will interpret that exact same naive value as two different real moments in time, hours apart.

Fix

Use timezone-aware datetimes everywhere a specific moment in time matters — attach tzinfo=timezone.utc (or the specific zone via zoneinfo) explicitly, so the same datetime object means the same real moment no matter which machine's local settings are evaluating it.

issue_55_timezone_mismatch.py
from datetime import datetime, timezone, timedelta

def schedule_report(local_hour):
    # BUG: naive datetime -- no timezone attached, so "9" means "9 in
    # whatever timezone happens to be assumed", which differs by environment
    return datetime(2026, 7, 9, local_hour, 0, 0)

dev_scheduled = schedule_report(9)  # developer tested this on a laptop set to US/Eastern
print(f"naive datetime (no tzinfo attached): {dev_scheduled}")
print(f"tzinfo: {dev_scheduled.tzinfo}")

# in production, the server's system clock and application both run in UTC --
# the exact same naive datetime object now means a DIFFERENT real moment in time
utc_interpretation = dev_scheduled.replace(tzinfo=timezone.utc)
eastern_interpretation = dev_scheduled.replace(tzinfo=timezone(timedelta(hours=-4)))
print(f"if treated as UTC:        {utc_interpretation.isoformat()}")
print(f"if treated as US/Eastern: {eastern_interpretation.isoformat()}")
print(f"gap between interpretations: {utc_interpretation - eastern_interpretation}")
actual output (Python 3.14.4)
naive datetime (no tzinfo attached): 2026-07-09 09:00:00
tzinfo: None
if treated as UTC:        2026-07-09T09:00:00+00:00
if treated as US/Eastern: 2026-07-09T09:00:00-04:00
gap between interpretations: -1 day, 20:00:00

-1 day, 20:00:00 is Python's way of expressing a negative four-hour timedelta — the same naive clock reading is four real hours apart depending purely on which timezone assumption is applied to it, exactly the gap between UTC and US/Eastern.

#56

A file write that fails only on a locked-down fresh server

Symptom

A file-upload handler that's been reliable for months suddenly fails on every request after a routine server migration — with a PermissionError, not a FileNotFoundError.

Root cause

This is issue #9's distinction (FileNotFoundError vs. PermissionError) showing up at deployment time instead of at request time. A developer's local machine or an old server, set up manually over time, often accumulates permissive file permissions on its working directories. A freshly provisioned server — especially one built from a hardened base image — may create that same directory with much stricter default permissions, denying write access to the process's user.

Fix

Explicitly set required permissions as part of the deployment process (a Dockerfile RUN chmod/chown step, an infrastructure-as-code rule) rather than relying on whatever a server happens to default to — permissions should be declared and version-controlled, not discovered by trial and error after a migration.

issue_56_file_permission_fresh_server.py
import os
import stat

def write_upload(path, content):
    with open(path, "w") as f:
        f.write(content)

target_dir = "/tmp/ch26_uploads"
os.makedirs(target_dir, exist_ok=True)
os.chmod(target_dir, stat.S_IRUSR | stat.S_IXUSR)  # simulate a locked-down fresh server: read+execute only, no write

try:
    write_upload(f"{target_dir}/file1.txt", "hello")
finally:
    os.chmod(target_dir, stat.S_IRWXU)  # restore so this scratch dir can be cleaned up
    os.rmdir(target_dir)
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_56_file_permission_fresh_server.py", line 13, in <module>
    write_upload(f"{target_dir}/file1.txt", "hello")
    ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "issue_56_file_permission_fresh_server.py", line 5, in write_upload
    with open(path, "w") as f:
         ~~~~^^^^^^^^^^^
PermissionError: [Errno 13] Permission denied: '/tmp/ch26_uploads/file1.txt'
#57

DEBUG=True shipped straight to production

Symptom

An internal database hostname, plus a full stack trace of application internals, shows up directly in an error page served to a real, external user.

Root cause

Web frameworks like Flask and FastAPI (Chapter 22) offer a debug mode specifically to help local development: it shows detailed tracebacks in the browser and, in some frameworks, even exposes an interactive in-browser debugger console. That's an enormous convenience while developing locally, and an equally enormous information disclosure risk (internal hostnames, file paths, sometimes even a remote code execution surface via the interactive console) if the exact same flag ships unchanged to a publicly reachable production deployment.

Fix

Drive debug mode from an environment variable that defaults to False/off, and never hardcode debug=True directly in application code that also runs in production — treat "is this environment allowed to show internals to the client" as a deployment-time decision, not a code-time one.

issue_57_debug_true_shipped.py
class FakeApp:
    """A tiny stand-in for a Flask/FastAPI-style app object, just enough
    to demonstrate what DEBUG=True actually exposes -- without needing
    the real dependency installed for this repro."""
    def __init__(self, debug):
        self.debug = debug

    def handle_error(self, exc):
        if self.debug:
            # BUG: debug mode echoes the raw exception and a stack trace
            # straight into the HTTP response body -- fine on a laptop,
            # a serious information leak in production
            return f"500 Internal Server Error\n\nTraceback:\n{exc!r}\n\nDEBUG=True: interactive debugger enabled at /console"
        else:
            return "500 Internal Server Error"

app_dev = FakeApp(debug=True)   # correct for local development
app_prod = FakeApp(debug=True)  # BUG: same DEBUG=True value shipped to production

try:
    raise ValueError("could not connect to internal-db-host-03.internal:5432")
except ValueError as exc:
    print("--- response body a real attacker would see in prod ---")
    print(app_prod.handle_error(exc))
actual output (Python 3.14.4)
--- response body a real attacker would see in prod ---
500 Internal Server Error

Traceback:
ValueError('could not connect to internal-db-host-03.internal:5432')

DEBUG=True: interactive debugger enabled at /console

The internal hostname internal-db-host-03.internal — information that should never leave the internal network — is now sitting in a response any external visitor can trigger just by causing an error.

#58

A hardcoded localhost database URL

Symptom

A service that connects to its database perfectly on every developer's machine refuses to connect at all once deployed — with a connection-refused error, not an authentication or permissions error.

Root cause

On a developer's machine, localhost genuinely does have a database server running — installed locally, or running in a local Docker container mapped to that port. "localhost" hardcoded into source code isn't a placeholder that gets swapped out; it's a literal value that means exactly the same thing everywhere it runs. In a production container, "localhost" refers to the container itself, which has no database server running inside it — the real database is a separate host entirely.

Fix

Read connection details from configuration (environment variables, a config file injected at deploy time) rather than hardcoding them — the exact same pattern as issue #1 and #53: values that differ by environment belong in configuration, not in source code.

issue_58_hardcoded_localhost.py
import socket

def get_database_url():
    # BUG: hardcoded straight into the source instead of read from
    # environment/config -- works great until this code runs anywhere
    # other than the developer's own machine
    return "postgresql://localhost:5432/myapp"

def connect():
    url = get_database_url()
    host, port = "localhost", 5432
    # simulate what actually happens in a production container: there is
    # no database server listening on ITS OWN localhost
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(1)
    try:
        sock.connect((host, port))
    finally:
        sock.close()

connect()
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_58_hardcoded_localhost.py", line 21, in <module>
    connect()
    ~~~~~~~^^
  File "issue_58_hardcoded_localhost.py", line 17, in connect
    sock.connect((host, port))
    ~~~~~~~~~~~~^^^^^^^^^^^^^^
ConnectionRefusedError: [Errno 111] Connection refused
#59

A third-party import that fails before your own config has loaded

Symptom

An application crashes before printing a single line of its own log output — the very first thing to fail is an import statement, near the top of the entry-point file.

Root cause

Chapter 11 covered that a module's code runs once, at first import, top to bottom — including any setup logic the module's own author put at import time. Some SDKs (particularly ones that validate credentials, open connections, or read config as soon as they're imported) fail immediately if their required setup isn't ready yet. Placing that import at the very top of a file, before the application's own environment/config loading step has run, means the SDK's import-time check can run before the very thing it needs has been set up.

Fix

Load and validate configuration first, at the very top of the entry point, before importing anything whose own import has side effects that depend on that configuration — or better, prefer libraries that defer their setup to an explicit init()/configure() call rather than doing it implicitly at import time.

issue_59_dependency_import_side_effects.py
import sys
import types

# simulate a third-party package whose __init__.py has an import-time side
# effect (e.g. reading a config file, connecting to a service) that only
# succeeds when a specific environment variable is present
fake_pkg = types.ModuleType("analytics_sdk")

def _fake_init():
    import os
    if "ANALYTICS_API_KEY" not in os.environ:
        raise RuntimeError("ANALYTICS_API_KEY must be set before importing analytics_sdk")
    return "initialized"

fake_pkg._init = _fake_init
sys.modules["analytics_sdk"] = fake_pkg

# BUG: the app imports this SDK at module load time, at the very top of
# the file, before its own config-loading step has even run -- so the
# import itself fails if the env var isn't set yet
import os
if "ANALYTICS_API_KEY" in os.environ:
    del os.environ["ANALYTICS_API_KEY"]

import analytics_sdk
analytics_sdk._init()
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_59_dependency_import_side_effects.py", line 26, in <module>
    analytics_sdk._init()
    ~~~~~~~~~~~~~~~~~~~^^
  File "issue_59_dependency_import_side_effects.py", line 12, in _fake_init
    raise RuntimeError("ANALYTICS_API_KEY must be set before importing analytics_sdk")
RuntimeError: ANALYTICS_API_KEY must be set before importing analytics_sdk

This repro builds a small fake module with types.ModuleType to stand in for a real third-party SDK, since the actual bug is about import-time ordering and environment setup, not about any specific package — the pattern (an import-time side effect that depends on configuration the app hasn't loaded yet) is what matters, and it applies to plenty of real SDKs.

#60

A script that only imports correctly from inside an IDE

Symptom

A deployment health-check script that a developer runs constantly from their editor, without issue, fails with ModuleNotFoundError the very first time it's run from a plain terminal on a fresh server.

Root cause

Chapter 11 covered how Python resolves imports by searching sys.path. Many IDEs and editors automatically add a project's src/ folder to sys.path (via a workspace setting, a .pth file, or an editable install) as a convenience — entirely invisibly to the developer, who never has to think about it. A bare python scripts/deploy_check.py, run from a plain shell on a server with none of that IDE tooling present, has no such convenience: src/ was never added to the path, so the import genuinely can't find the package.

Fix

Don't depend on IDE-specific path magic for anything that needs to run outside the IDE — install the project properly (pip install -e .) so the package is genuinely importable everywhere, or set PYTHONPATH explicitly as part of how the script is invoked in deployment.

deploy_check.py
# BUG: this script relies on "src/" being importable -- true on the
# developer's machine, where their editor/IDE (or an installed editable
# package) already adds "src/" to sys.path, but a bare
# `python scripts/deploy_check.py` on a fresh production server has
# no such thing configured
from myapp.helpers import greet
print(greet("world"))
actual output (Python 3.14.4, run as `python scripts/deploy_check.py` from the project root, with no PYTHONPATH set)
Traceback (most recent call last):
  File "scripts/deploy_check.py", line 6, in <module>
    from myapp.helpers import greet
ModuleNotFoundError: No module named 'myapp'

The exact same script, run with PYTHONPATH=src set first, imports and runs without any error at all — nothing about the script itself needs to change, only how (and with what environment) it's invoked.

Quick recap
  • Every bug in this category is a difference between environments, not a bug in the logic itself — the code is often completely correct for the environment it was tested in.
  • "Works on my machine" is a real, specific class of bug with real causes (Python version, dependency versions, environment variables, working directory, file permissions, timezone) — not a joke about flaky developers.
  • The fix for nearly every entry here is the same underlying principle: make environments identical (pinned versions, explicit config, no IDE-only conveniences) instead of relying on them happening to match.
In the Real World (Category 6)
Category 7 of 8

7. Database & API Failures

Chapters 19 and 21 covered talking to APIs and databases when everything goes right. This category is about the much larger set of ways that conversation can go wrong — a malicious or malformed input, a connection that's never released, a dependency that's slow, down, or lying about what it just did. The database examples below use Python's built-in sqlite3 module so every repro is genuinely runnable without any external service.

#61

SQL injection from string-formatted queries

Symptom

A user lookup that's supposed to return exactly one account instead returns every account in the entire table, for certain unusual-looking input.

Root cause

Chapter 21 covered running SQL from Python, but building the query with an f-string means the username value becomes literal SQL text, not data. An input like ' OR '1'='1 closes the string literal early and adds a condition that's always true — turning WHERE username = '' into WHERE username = '' OR '1'='1', which matches every row in the table. This is the single most well-known real-world security vulnerability class, and it comes directly from mixing code and data.

Fix

Always use parameterized queries — pass values as separate arguments (conn.execute(query, (username,))) rather than formatting them into the SQL string. The database driver handles escaping correctly, and a malicious value can never be interpreted as part of the SQL structure.

issue_61_sql_injection.py
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER, username TEXT, is_admin INTEGER)")
conn.execute("INSERT INTO users VALUES (1, 'alice', 0)")
conn.execute("INSERT INTO users VALUES (2, 'bob', 1)")
conn.commit()

def find_user_vulnerable(username):
    # BUG: string formatting builds the SQL directly -- a malicious
    # username can inject its own SQL
    query = f"SELECT * FROM users WHERE username = '{username}'"
    return conn.execute(query).fetchall()

# a normal lookup
print("normal lookup:", find_user_vulnerable("alice"))

# a malicious "username" that breaks out of the string literal
malicious_input = "' OR '1'='1"
print("malicious lookup:", find_user_vulnerable(malicious_input))
print("^ returned EVERY row, not just one matching user -- classic SQL injection")

def find_user_safe(username):
    # FIX: parameterized query -- the driver handles escaping, the value
    # is never concatenated into the SQL text itself
    query = "SELECT * FROM users WHERE username = ?"
    return conn.execute(query, (username,)).fetchall()

print("safe lookup with same malicious input:", find_user_safe(malicious_input))
actual output (Python 3.14.4)
normal lookup: [(1, 'alice', 0)]
malicious lookup: [(1, 'alice', 0), (2, 'bob', 1)]
^ returned EVERY row, not just one matching user -- classic SQL injection
safe lookup with same malicious input: []

The parameterized version correctly returns an empty list — there's genuinely no user literally named ' OR '1'='1 — because the driver treats the entire malicious string as one literal value to search for, never as SQL syntax to execute.

Thought process: this is one of the few bugs in this entire chapter with zero acceptable exceptions — there's no version of "building SQL with string formatting is fine here because..." that holds up. The right instinct is to treat any user-controllable value that ends up in a SQL string as an active threat, by default, regardless of how unlikely a real attack seems for a given feature.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function find_user(conn, username) using sqlite3 that looks up a user by username, using a parameterized query (never string formatting or concatenation) so it's safe against SQL injection. Then demonstrate the difference by calling it with the malicious input "' OR '1'='1" and showing it returns zero rows, not every row in the table.
#62

A connection pool exhausted by connections that are never returned

Symptom

A service handles the first handful of requests fine, then every subsequent database-backed request starts failing with a "pool exhausted" or "too many connections" error — and it never recovers on its own.

Root cause

Chapter 21's pattern of opening a connection and doing work with it has a step that's easy to skip under pressure: releasing the connection back to the pool when done. A connection pool has a fixed maximum size; every call that checks one out without ever checking it back in permanently reduces the pool's effective capacity by one, until nothing is left to hand out to the next caller.

Fix

Always release (or close) a connection in a finally block or, better, a with block — so it's returned to the pool no matter whether the code using it succeeded or raised an exception partway through.

issue_62_connection_pool_exhaustion.py
import sqlite3

class TinyConnectionPool:
    """A minimal stand-in for a real connection pool (e.g. from SQLAlchemy
    or psycopg2.pool), just enough to demonstrate exhaustion behavior."""
    def __init__(self, db_path, max_connections):
        self.db_path = db_path
        self.max_connections = max_connections
        self._checked_out = 0

    def get_connection(self):
        if self._checked_out >= self.max_connections:
            raise RuntimeError(
                f"connection pool exhausted: {self._checked_out}/{self.max_connections} "
                f"connections checked out and never returned"
            )
        self._checked_out += 1
        return sqlite3.connect(self.db_path)
    # BUG: there is no release_connection() call anywhere below -- every
    # caller that finishes with a connection is supposed to give it back,
    # but nothing enforces that

pool = TinyConnectionPool(":memory:", max_connections=5)

def run_query_leaky():
    conn = pool.get_connection()  # BUG: connection is never closed/returned
    result = conn.execute("SELECT 1").fetchone()
    return result
    # conn.close() is never reached -- and there's no "with" block either

for i in range(5):
    run_query_leaky()

run_query_leaky()  # the 6th call has nothing left to check out
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_62_connection_pool_exhaustion.py", line 34, in <module>
    run_query_leaky()  # the 6th call has nothing left to check out
    ~~~~~~~~~~~~~~~^^
  File "issue_62_connection_pool_exhaustion.py", line 26, in run_query_leaky
    conn = pool.get_connection()  # BUG: connection is never closed/returned
  File "issue_62_connection_pool_exhaustion.py", line 13, in get_connection
    raise RuntimeError(
    ...<2 lines>...
    )
RuntimeError: connection pool exhausted: 5/5 connections checked out and never returned
#63

The N+1 query pattern

Symptom

A "list books with their authors" endpoint that's fast in testing with a handful of books becomes noticeably slow once the real database has more than a few hundred — and the slowdown is roughly proportional to the number of books, not the complexity of the query.

Root cause

This is Category 2's nested-loop pattern (issue #14), but expressed as database round-trips instead of in-memory list scans: one query fetches all the books, and then a separate query fetches each book's author, one at a time, inside a loop. For 150 books, that's 151 total queries — and every query is a full network round-trip to the database, which is far slower than any in-memory operation.

Fix

Use a JOIN to fetch books and their authors together in a single query — the database is specifically built to do this kind of combination efficiently, in one round-trip, rather than paying network latency once per row.

issue_63_n_plus_one.py
import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE authors (id INTEGER, name TEXT)")
conn.execute("CREATE TABLE books (id INTEGER, title TEXT, author_id INTEGER)")
for i in range(1, 51):
    conn.execute("INSERT INTO authors VALUES (?, ?)", (i, f"Author {i}"))
    for j in range(3):
        conn.execute("INSERT INTO books VALUES (?, ?, ?)", (i * 10 + j, f"Book {i}-{j}", i))
conn.commit()

query_count = 0

def execute_counted(query, params=()):
    global query_count
    query_count += 1
    return conn.execute(query, params)

def list_books_with_authors_slow():
    # BUG: one query to get all books, then a SEPARATE query per book to
    # fetch its author -- the classic N+1 pattern
    books = execute_counted("SELECT id, title, author_id FROM books").fetchall()
    results = []
    for book_id, title, author_id in books:
        author = execute_counted("SELECT name FROM authors WHERE id = ?", (author_id,)).fetchone()
        results.append((title, author[0]))
    return results

results = list_books_with_authors_slow()
print(f"books returned: {len(results)}")
print(f"total queries executed: {query_count}  (1 + one-per-book)")

query_count = 0

def list_books_with_authors_fast():
    # FIX: a single JOIN replaces the N+1 queries with exactly 1
    rows = execute_counted(
        "SELECT books.title, authors.name FROM books "
        "JOIN authors ON books.author_id = authors.id"
    ).fetchall()
    return rows

results_fast = list_books_with_authors_fast()
print(f"books returned (joined): {len(results_fast)}")
print(f"total queries executed: {query_count}")
actual output (Python 3.14.4)
books returned: 150
total queries executed: 151  (1 + one-per-book)
books returned (joined): 150
total queries executed: 1
#64

Not handling a 429 rate-limit response

Symptom

A script that fetches several pages from a third-party API works fine for the first few pages, then crashes with a KeyError partway through — on a field that was present in every earlier response.

Root cause

Chapter 19 covered parsing a JSON response body, but assumed every response has the same shape. Once an API's rate limit is exceeded, it typically returns a 429 status with a completely different body (an error description, not the requested data) — code that reaches straight for response.json()["data"] without first checking the status code has no way to distinguish a successful response from a rate-limited one until the KeyError happens.

Fix

Check the status code before trusting the response body's shape, and implement a retry with exponential backoff specifically for 429s (many APIs also return a Retry-After header telling you exactly how long to wait) — rather than assuming every response that comes back is the one that was asked for.

issue_64_rate_limit_429.py
class FakeAPIClient:
    """Stand-in for a real HTTP client (e.g. requests) hitting a rate-limited
    API, without needing network access for this repro."""
    def __init__(self):
        self.call_count = 0

    def get(self, endpoint):
        self.call_count += 1
        if self.call_count > 3:
            return FakeResponse(429, {"error": "rate limit exceeded"})
        return FakeResponse(200, {"data": f"result-{self.call_count}"})

class FakeResponse:
    def __init__(self, status_code, body):
        self.status_code = status_code
        self._body = body
    def json(self):
        return self._body

client = FakeAPIClient()

def fetch_all_pages_naive(pages):
    # BUG: no handling for a 429 at all -- just assumes every response is a success
    results = []
    for _ in range(pages):
        resp = client.get("/data")
        results.append(resp.json()["data"])  # KeyError once a 429 body has no "data" key
    return results

fetch_all_pages_naive(5)
actual output (Python 3.14.4)
Traceback (most recent call last):
  File "issue_64_rate_limit_429.py", line 30, in <module>
    fetch_all_pages_naive(5)
    ~~~~~~~~~~~~~~~~~~~~~^^^
  File "issue_64_rate_limit_429.py", line 27, in fetch_all_pages_naive
    results.append(resp.json()["data"])  # KeyError once a 429 body has no "data" key
                   ~~~~~~~~~~~^^^^^^^^
KeyError: 'data'
#65

No timeout set on a network call, so it hangs forever

Symptom

A request to a downstream service occasionally never returns at all — not slow, not erroring, just permanently stuck — and every worker thread or process that gets stuck this way is effectively lost until the whole service is restarted.

Root cause

A network call with no timeout configured will wait indefinitely for a response, by design — that's the default behavior of raw sockets and most HTTP client libraries unless a timeout is explicitly requested. If the remote server is overloaded, or a firewall silently drops the packets rather than actively refusing the connection, there is nothing to make the call fail on its own; it just waits, forever, holding whatever resources (a thread, a connection) it was using.

Fix

Always set an explicit timeout on any network call — a deliberately failed request that can be retried or reported is always better than a silently hung one. Most production incidents involving a "stuck" service trace back to exactly this: one downstream call with no timeout, upstream of everything else.

issue_65_no_timeout_hang.py
import socket

def fetch_from_slow_host(host, port, request_bytes, timeout=None):
    # BUG: no timeout is set -- if the server never responds (a firewall
    # black-holing the connection, an overloaded backend), this call can
    # block forever
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.settimeout(timeout)  # None means "block forever" -- the actual bug
    sock.connect((host, port))
    sock.sendall(request_bytes)
    return sock.recv(4096)

# 10.255.255.1 is a well-known non-routable address commonly used to
# simulate a host that will never respond (packets are silently dropped)
try:
    fetch_from_slow_host("10.255.255.1", 80, b"GET / HTTP/1.0\r\n\r\n", timeout=2)
except TimeoutError as e:
    print(f"with timeout=2 set explicitly, it fails fast instead of hanging: {e!r}")
actual output (Python 3.14.4)
with timeout=2 set explicitly, it fails fast instead of hanging: TimeoutError('timed out')

This repro deliberately demonstrates the fixed version (with a timeout) rather than the actual bug, for a practical reason: reproducing the real hang would mean this script never finishes running. Calling fetch_from_slow_host(...) with timeout=None (the buggy default) against an unreachable host is exactly what the fix prevents — the function would simply never return.

#66

Retrying a non-idempotent request and double-charging a customer

Symptom

A payment retry mechanism that's supposed to make the system more reliable ends up charging a customer twice for a single purchase.

Root cause

Chapter 12 covered retrying operations after a failure — but retrying is only safe when the operation is idempotent, meaning doing it twice has the same effect as doing it once. A payment charge is not naturally idempotent: if the server-side charge succeeded but the response was lost on the way back (a timeout, a dropped connection), the client has no way to know that, and blindly retrying the same request charges the customer a second time for what the client believes is still a single failed attempt.

Fix

Attach a unique idempotency key to the request (generated once per logical operation, reused on every retry) so the server can recognize "I've already processed this exact request" and return the original result instead of charging again — most real payment APIs (Stripe, for example) support this pattern natively.

issue_66_retry_without_idempotency.py
class FakePaymentAPI:
    """Stand-in for a real payment gateway client."""
    def __init__(self):
        self.charges = []
        self.call_count = 0

    def charge(self, account_id, amount):
        self.call_count += 1
        if self.call_count == 1:
            # simulate the response getting lost on the way back to the
            # caller (a network blip) even though the charge itself succeeded
            self.charges.append((account_id, amount))
            raise TimeoutError("response timed out (but the server-side charge already happened)")
        self.charges.append((account_id, amount))
        return "charged"

api = FakePaymentAPI()

def charge_with_naive_retry(account_id, amount, attempts=3):
    # BUG: blindly retries the same request on any failure, with no way
    # to tell the server "this is the same logical charge, don't repeat it"
    last_error = None
    for _ in range(attempts):
        try:
            return api.charge(account_id, amount)
        except TimeoutError as e:
            last_error = e
            continue
    raise last_error

result = charge_with_naive_retry("acct-42", 99.00)
print(f"retry result: {result}")
print(f"total charges recorded: {len(api.charges)}")
print(f"charges: {api.charges}")
print("customer was charged twice for one logical request")
actual output (Python 3.14.4)
retry result: charged
total charges recorded: 2
charges: [('acct-42', 99.0), ('acct-42', 99.0)]
customer was charged twice for one logical request

Thought process: "just add a retry loop" is a dangerously incomplete answer to "this API call sometimes fails" — whether retrying is safe depends entirely on whether the operation is idempotent, and that's a property of the specific action (a payment vs. a read-only lookup), not something a generic retry wrapper can know on its own.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function charge_with_idempotency_key(api, account_id, amount, idempotency_key) that retries a payment charge up to 3 times on TimeoutError, but passes the same idempotency_key on every attempt so a payment gateway that supports idempotency keys will recognize repeated attempts as the same logical charge and avoid charging twice. Explain why a plain retry loop without an idempotency key is unsafe specifically for a non-idempotent operation like a payment charge.
#67

Trusting an API response without validating it first

Symptom

A weather display crashes with a TypeError for one specific city, while working correctly for every other city passed to the exact same function.

Root cause

Chapter 19 covered parsing JSON responses, but not every field in a real API's response is guaranteed to be populated — a weather API might legitimately return null/None for a temperature it couldn't determine. Code that does arithmetic directly on a field pulled from a response (forecast["temperature_c"] * 9 / 5 + 32) is implicitly assuming that field is always a usable number, which the API itself never actually promised.

Fix

Validate response data at the boundary where it enters the system — check for None (or use a schema-validation library like pydantic) before doing anything that assumes a specific type, and decide explicitly what should happen when a field is missing or unusable, rather than letting the first arithmetic operation on it decide by crashing.

issue_67_unvalidated_api_response.py
class FakeWeatherAPI:
    def get_forecast(self, city):
        # simulates a real API that sometimes returns a valid payload and
        # sometimes returns None for a field it couldn't determine
        if city == "Unknown City":
            return {"city": city, "temperature_c": None}
        return {"city": city, "temperature_c": 22.5}

api = FakeWeatherAPI()

def describe_weather(city):
    forecast = api.get_forecast(city)
    # BUG: assumes temperature_c is always a usable number, never checks
    # for None before doing arithmetic on it
    temp_f = forecast["temperature_c"] * 9 / 5 + 32
    return f"{city}: {temp_f}F"

print(describe_weather("Chicago"))
describe_weather("Unknown City")
actual output (Python 3.14.4)
Chicago: 72.5F
Traceback (most recent call last):
  File "issue_67_unvalidated_api_response.py", line 19, in <module>
    describe_weather("Unknown City")
    ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^
  File "issue_67_unvalidated_api_response.py", line 15, in describe_weather
    temp_f = forecast["temperature_c"] * 9 / 5 + 32
             ~~~~~~~~~~~~~~~~~~~~~~~~~~^~~
TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
#68

Reusing a database connection after it's been closed

Symptom

A function that reads a setting from the database works fine the first time it's called, then fails on every subsequent call, with an error about the connection being closed — even though nothing in the calling code closed it deliberately.

Root cause

Code held onto a database connection object across a period during which something else (a connection pool recycling it, a restart, an explicit .close() call elsewhere in the codebase) invalidated it. Once a connection is closed, it stays closed — there's no automatic reconnection, and every operation attempted on it afterward fails immediately, since the underlying resource it wraps genuinely no longer exists.

Fix

Don't hold long-lived references to a single connection object across a function or module's entire lifetime — acquire a fresh connection (or one from a pool) for each unit of work, or wrap database access in a helper that detects a closed/invalid connection and transparently reconnects.

issue_68_stale_connection_reuse.py
import sqlite3
import os

db_path = "/tmp/ch26_stale_conn_demo.db"
if os.path.exists(db_path):
    os.remove(db_path)

conn = sqlite3.connect(db_path)
conn.execute("CREATE TABLE settings (key TEXT, value TEXT)")
conn.execute("INSERT INTO settings VALUES ('theme', 'dark')")
conn.commit()

def read_setting_cached(cached_conn, key):
    return cached_conn.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()

print("first read:", read_setting_cached(conn, "theme"))

conn.close()  # simulate the underlying connection being torn down (e.g. a DB restart, a pool eviction)
os.remove(db_path)  # and now even the file backing it is gone

# BUG: code elsewhere held onto `conn` and keeps reusing it after it was closed
read_setting_cached(conn, "theme")
actual output (Python 3.14.4)
first read: ('dark',)
Traceback (most recent call last):
  File "issue_68_stale_connection_reuse.py", line 22, in <module>
    read_setting_cached(conn, "theme")
    ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^
  File "issue_68_stale_connection_reuse.py", line 14, in read_setting_cached
    return cached_conn.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
           ~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.ProgrammingError: Cannot operate on a closed database.
#69

A write that "succeeds" but was never actually committed

Symptom

An inventory deduction runs without error, but a second part of the system checking the same inventory table reports the old, un-deducted quantity — as if the update never happened.

Root cause

Chapter 21 covered running an UPDATE statement, but a database transaction isn't visible to other connections until it's explicitly committed. Without conn.commit(), the change exists only inside this specific connection's pending transaction — correct as far as this connection is concerned, invisible to everyone else, and vulnerable to being silently lost entirely if the connection is dropped before a commit ever happens.

Fix

Always call conn.commit() after a write that should actually persist — many ORMs and frameworks handle this automatically at the end of a request, but raw sqlite3/psycopg2-style code has to do it explicitly, and it's easy to forget on a code path that isn't exercised by casual manual testing.

issue_69_transaction_not_committed.py
import sqlite3

conn_writer = sqlite3.connect("/tmp/ch26_txn_demo.db")
conn_writer.execute("DROP TABLE IF EXISTS inventory")
conn_writer.execute("CREATE TABLE inventory (item TEXT, qty INTEGER)")
conn_writer.execute("INSERT INTO inventory VALUES ('widget', 100)")
conn_writer.commit()

def deduct_stock_missing_commit(conn, item, amount):
    conn.execute("UPDATE inventory SET qty = qty - ? WHERE item = ?", (amount, item))
    # BUG: no conn.commit() -- the change lives only in this connection's
    # uncommitted transaction

deduct_stock_missing_commit(conn_writer, "widget", 30)

# a second, independent connection -- standing in for a different process
# or request checking the "real" committed state of the database
conn_reader = sqlite3.connect("/tmp/ch26_txn_demo.db")
qty_seen_by_reader = conn_reader.execute("SELECT qty FROM inventory WHERE item = 'widget'").fetchone()
print(f"quantity another connection sees: {qty_seen_by_reader}")
print("the deduction is invisible to anyone else until commit() is called")

conn_writer.commit()  # now actually commit it
qty_after_commit = conn_reader.execute("SELECT qty FROM inventory WHERE item = 'widget'").fetchone()
print(f"quantity after the writer finally commits: {qty_after_commit}")

conn_writer.close()
conn_reader.close()
actual output (Python 3.14.4)
quantity another connection sees: (100,)
the deduction is invisible to anyone else until commit() is called
quantity after the writer finally commits: (70,)
#70

Treating "the API call failed" as "the resource doesn't exist"

Symptom

Every product shows as "out of stock" for several minutes, across the entire catalog, even though inventory levels haven't actually changed — then it resolves on its own with no code deployed.

Root cause

This is issue #6's broad-except pattern, applied to a dependency instead of a business-logic exception. Catching Exception broadly around an API call and returning False ("not in stock") on any failure conflates two completely different situations: "the inventory service says this item has zero stock" and "the inventory service is unreachable and we have no idea." Both produce the exact same user-facing result, even though only one of them is actually true.

Fix

Distinguish a definitive answer from a failure to get an answer — catch the specific exception type a downed dependency raises, and respond differently: show a "temporarily unable to check availability" state, use a cached last-known value, or fail the request loudly, rather than silently reinterpreting "unknown" as "no."

issue_70_broad_except_on_api_call.py
class FakeInventoryAPI:
    def __init__(self):
        self.call_count = 0
    def check_stock(self, sku):
        self.call_count += 1
        if self.call_count == 2:
            raise ConnectionError("upstream inventory service unreachable")
        return {"sku": sku, "in_stock": True}

api = FakeInventoryAPI()

def is_available_broad_except(sku):
    try:
        result = api.check_stock(sku)
        return result["in_stock"]
    except Exception:
        # BUG: ANY failure -- a real network outage, a bug, a typo'd key --
        # is treated identically to "not in stock", which is actively wrong:
        # the service being down doesn't mean the item is unavailable
        return False

print(f"sku-1 available: {is_available_broad_except('sku-1')}")
print(f"sku-2 available (service actually down): {is_available_broad_except('sku-2')}")
print("^ reported as 'not available' when the real problem was a downed dependency --")
print("  customers see 'out of stock' on items that may well be in stock")
actual output (Python 3.14.4)
sku-1 available: True
sku-2 available (service actually down): False
^ reported as 'not available' when the real problem was a downed dependency --
  customers see 'out of stock' on items that may well be in stock
Quick recap
  • SQL injection (issue #61) and unhandled network hangs (issue #65) are two of the most consequential bugs in this entire chapter — one is a direct security vulnerability, the other can take down an entire service by exhausting its available workers.
  • A resource acquired from a pool (a connection) needs an equally explicit release, matching Category 3's file-handle lesson — forgetting either one eventually exhausts a fixed-size resource.
  • Not every failure means the same thing: "the answer is no" and "I couldn't get an answer" are different situations that deserve different handling, not the same broad except block (issue #70).
In the Real World (Category 7)
Category 8 of 8

8. Logging & Observability

Every earlier category in this chapter assumed the bug was eventually discovered somehow. This final category is about that "somehow" — the difference between an incident that's diagnosed in five minutes from a clear log trail, and one that takes a week because the evidence that would have explained it was never captured at all.

#71

print() statements instead of structured logging

Symptom

A developer insists a piece of code definitely ran and logged useful diagnostic info — but nothing matching it can be found anywhere in the production log aggregator.

Root cause

print() writes to standard output; the logging module writes through a configurable pipeline of handlers, levels, and formatters. In many real deployments those two things are captured completely differently — stdout might go to a container's raw log stream while the actual logging pipeline ships to a searchable aggregator (or vice versa). And separately, logging.info() calls are silently dropped entirely if the effective log level (default: WARNING) is set above INFO.

Fix

Use the logging module everywhere in application code, never print(), so every message flows through one consistent, configurable pipeline — and explicitly configure the logging level appropriate for each environment (more verbose in development, less in production) rather than relying on the library's default.

issue_71_print_instead_of_logging.py
import logging

def process_order(order_id):
    print(f"processing order {order_id}")       # BUG: goes to stdout, not to the log pipeline
    logging.info(f"processing order {order_id}")  # invisible: default logging level is WARNING

process_order(42)
print(f"root logger's effective level: {logging.getLogger().getEffectiveLevel()} (WARNING=30, INFO=20)")
print("in a real deployment, stdout from print() often isn't collected the same way")
print("as the structured logging pipeline is -- and logging.info() here never even fires")
actual output (Python 3.14.4)
processing order 42
root logger's effective level: 30 (WARNING=30, INFO=20)
in a real deployment, stdout from print() often isn't collected the same way
as the structured logging pipeline is -- and logging.info() here never even fires

Only the print() line actually produced visible output — the logging.info() call ran without error, but silently produced nothing, because level 20 (INFO) is below the root logger's default effective level of 30 (WARNING).

#72

Secrets accidentally logged in plaintext

Symptom

A security review discovers that plaintext passwords and live API tokens have been sitting in a log aggregator, searchable by anyone with log access, for months.

Root cause

A debug-friendly log line that dumps "the whole request context" is convenient while actively troubleshooting — it's also indiscriminate. It has no concept of which fields are sensitive, so a password or API token passed through the same function as an ordinary username gets logged with exactly the same lack of ceremony, and log files are typically retained (and searchable) far longer than anyone consciously decided they should be.

Fix

Never log raw credentials, tokens, or other secrets — redact or omit sensitive fields explicitly before logging (password=***), and treat "does this log line contain anything sensitive" as a required check during code review, not an afterthought caught only by a later security audit.

issue_72_secrets_logged.py
import logging
import io

log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
logger = logging.getLogger("auth")
logger.addHandler(handler)
logger.setLevel(logging.INFO)

def authenticate(username, password, api_token):
    # BUG: logs the entire request context for "debugging", including
    # the raw password and API token -- exactly the kind of log line
    # that ends up searchable in a log aggregator for years
    logger.info(f"login attempt: username={username} password={password} token={api_token}")
    return username == "alice" and password == "correct-horse-battery-staple"

authenticate("alice", "correct-horse-battery-staple", api_token="sk_live_51H8x2KtestSECRET")

print("--- what actually landed in the log stream ---")
print(log_stream.getvalue())
print("the plaintext password and a live API token are now sitting in a log file")
actual output (Python 3.14.4)
--- what actually landed in the log stream ---
login attempt: username=alice password=correct-horse-battery-staple token=sk_live_51H8x2KtestSECRET

the plaintext password and a live API token are now sitting in a log file
#73

No correlation ID, so a distributed error can't be traced

Symptom

Three orders are processed around the same time, one of them fails somewhere in the middle of a multi-step process, and the logs make it completely impossible to tell which log lines belong to the failed order versus the two that succeeded.

Root cause

Each function in the pipeline logs its own step ("validating payment," "reserving inventory") with no identifier tying that specific log line back to the specific order it was processing. When multiple orders are processed around the same time — concurrently, or just close together — their log lines interleave in the output with nothing to distinguish which line belongs to which logical operation.

Fix

Generate a unique correlation ID (or request ID) at the start of each logical operation, and include it in every log line produced anywhere during that operation — then any log aggregator can filter to "everything that happened for order-102" with a single search, regardless of how many other operations were interleaved in the raw output.

issue_73_no_correlation_id.py
import logging
import io

log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
logger = logging.getLogger("orders")
logger.addHandler(handler)
logger.setLevel(logging.INFO)
handler.setFormatter(logging.Formatter("%(message)s"))

def validate_payment(order_id):
    logger.info("validating payment")  # BUG: no request/order identifier attached at all

def reserve_inventory(order_id):
    logger.info("reserving inventory")  # same problem

def process_order(order_id):
    validate_payment(order_id)
    reserve_inventory(order_id)

# three concurrent-looking orders being processed -- in a real system these
# interleave across threads/requests, and the log lines are indistinguishable
process_order("order-101")
process_order("order-102")
process_order("order-103")

print("--- log output with no correlation ID ---")
print(log_stream.getvalue())
print("^ which 'validating payment' line belongs to which order? unanswerable from this log alone")
actual output (Python 3.14.4)
--- log output with no correlation ID ---
validating payment
reserving inventory
validating payment
reserving inventory
validating payment
reserving inventory

^ which 'validating payment' line belongs to which order? unanswerable from this log alone

Thought process: correlation IDs matter most exactly when things go wrong for one specific request among thousands of others happening at the same time — which means the value of adding one is invisible in easy testing (with one request at a time) and only becomes obvious under real concurrent production load, which is precisely why it's easy to skip and expensive to have skipped.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write Python functions validate_payment(order_id) and reserve_inventory(order_id) that each log their action using Python's logging module, including the order_id in every single log message (e.g. via a logging.LoggerAdapter or an f-string prefix), so that filtering the log output for one specific order_id shows exactly and only that order's steps, even when multiple orders are processed interleaved in the same log stream.
#74

A log level misconfigured so INFO messages vanish in production

Symptom

When someone later asks "did this batch even start running?", there's no way to answer — the batch's start-of-processing log line simply doesn't exist anywhere, even though the code that should have produced it definitely ran.

Root cause

A production config sets the logger's level to WARNING "to reduce noise" — a reasonable-sounding goal that has a real cost: every logger.info() call anywhere in the codebase becomes silently invisible, not just the noisy ones. The line confirming a batch started, and the line confirming it processed however many records, are gone right alongside whatever noise the level change was actually trying to suppress.

Fix

Be deliberate about what counts as "noise" versus "the minimum evidence needed to reconstruct what happened" — key lifecycle events (a batch starting, finishing, or being skipped) usually belong at INFO or higher regardless of overall verbosity settings, precisely because their absence is what makes an incident unanswerable later.

issue_74_log_level_misconfigured.py
import logging
import io

log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))

logger = logging.getLogger("worker")
logger.addHandler(handler)
logger.setLevel(logging.WARNING)  # BUG: prod config sets this to WARNING "to reduce noise"

def process_batch(batch_id):
    logger.info(f"started batch {batch_id}")     # invisible at WARNING level
    logger.info(f"processed 500 records")          # invisible
    logger.warning(f"3 records skipped in batch {batch_id}")  # the only one that shows

process_batch("batch-77")

print("--- what actually got logged ---")
print(log_stream.getvalue() or "(nothing)")
print("both INFO lines -- the ones that would show the batch even STARTED -- are gone")
print("when someone asks 'did batch-77 run at all?', there's no evidence either way")
actual output (Python 3.14.4)
--- what actually got logged ---
WARNING: 3 records skipped in batch batch-77

both INFO lines -- the ones that would show the batch even STARTED -- are gone
when someone asks 'did batch-77 run at all?', there's no evidence either way
#75

Catching an exception, logging it, and continuing as if nothing happened

Symptom

An invoice for a customer with no payment method on file is marked "complete" in the system — even though the customer was never actually charged, and the error was correctly logged.

Root cause

This is issue #6's pattern (a real, specific exception caught and absorbed) with logging added on top — which makes it more dangerous, not less, because it now looks handled. The function logs the real error correctly, but then falls through to its normal "success" return value regardless of whether charge_customer() actually succeeded, so nothing downstream of this function has any way to know the charge failed.

Fix

Logging an error is not the same as handling it — the function's return value (or a re-raised exception) needs to reflect what actually happened, so callers and downstream systems can react correctly, rather than trusting a log line that only a human, only if they happen to be looking, will ever see.

issue_75_catch_log_continue.py
import logging
import io

log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger = logging.getLogger("billing")
logger.addHandler(handler)
logger.setLevel(logging.INFO)

def charge_customer(customer_id, amount):
    if customer_id == "cust-404":
        raise ValueError(f"no payment method on file for {customer_id}")
    return f"charged {customer_id} ${amount}"

def process_invoice(customer_id, amount):
    try:
        result = charge_customer(customer_id, amount)
        logger.info(f"invoice processed: {result}")
    except Exception as e:
        # BUG: logs the failure, then keeps going as if the invoice
        # succeeded -- nothing downstream ever finds out the charge failed
        logger.error(f"charge failed: {e}")
    return "invoice marked complete"  # BUG: always returns success, even on failure

status = process_invoice("cust-404", 250.00)
print(f"process_invoice() returned: {status!r}")
print("--- log output ---")
print(log_stream.getvalue())
print("the invoice is marked 'complete' even though the customer was never actually charged")
actual output (Python 3.14.4)
process_invoice() returned: 'invoice marked complete'
--- log output ---
ERROR: charge failed: no payment method on file for cust-404

the invoice is marked 'complete' even though the customer was never actually charged
#76

log.error(str(e)) instead of log.exception()

Symptom

A log line correctly reports that a row failed to import, and even shows the error message — but nobody can tell which line of code actually raised it, because a nearly identical ValueError message could come from three different places in the codebase.

Root cause

str(e) converts an exception to just its message text — everything else about the exception (which file, which line, the full call stack that led there) is discarded. logger.error(str(e)) logs only that bare message, which is often not unique or specific enough to pinpoint the actual failure once there's more than one place in the codebase that could raise a similarly worded error.

Fix

Use logger.exception(message) instead, called from inside an except block — it automatically attaches the full traceback to the log record, giving anyone reading the log the exact same information they'd have seen if the exception had crashed the program uncaught.

issue_76_error_str_not_exception.py
import logging
import io

log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
handler.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
logger = logging.getLogger("importer")
logger.addHandler(handler)
logger.setLevel(logging.INFO)

def parse_row(row):
    return int(row["amount"])  # raises if "amount" is missing or non-numeric

def import_rows(rows):
    for row in rows:
        try:
            parse_row(row)
        except Exception as e:
            # BUG: log.error(str(e)) discards the traceback entirely --
            # you get the error MESSAGE but no idea which line/function raised it
            logger.error(str(e))

import_rows([{"amount": "not-a-number"}])

print("--- with log.error(str(e)) ---")
print(log_stream.getvalue())
actual output (Python 3.14.4)
--- with log.error(str(e)) ---
ERROR: invalid literal for int() with base 10: 'not-a-number'

Switching to logger.exception("failed to parse row") instead produces dramatically more useful output from the exact same failure:

actual output with log.exception() (Python 3.14.4)
ERROR: failed to parse row
Traceback (most recent call last):
  File "issue_76_error_str_not_exception.py", line 38, in import_rows_fixed
    parse_row(row)
    ~~~~~~~~~^^^^^
  File "issue_76_error_str_not_exception.py", line 12, in parse_row
    return int(row["amount"])  # raises if "amount" is missing or non-numeric
ValueError: invalid literal for int() with base 10: 'not-a-number'

Same underlying failure, dramatically more information — the fixed version names the exact function and line (parse_row, then the specific int(...) call) that raised the error, not just what it said.

#77

Eagerly building an expensive log message that's never used

Symptom

A service is measurably slower than expected, even in production where debug logging is fully disabled — profiling points squarely at a function that's supposedly only used for debug output.

Root cause

An f-string is evaluated the instant Python reaches that line — logger.debug(f"...{expensive_summary(data)}") calls expensive_summary(data) immediately, building the entire formatted string, before logger.debug() even gets a chance to decide whether the message will actually be used. If the logger's level is above DEBUG (the common case in production), all of that formatting work happens for absolutely nothing — the result is computed and then immediately discarded.

Fix

For genuinely expensive debug-only computations, guard them with if logger.isEnabledFor(logging.DEBUG): so the expensive work only happens when the message will actually be used. (For ordinary log arguments, logging's built-in %-style lazy formatting — logger.debug("value: %s", x) — already defers formatting; it's specifically an expensive function call embedded in an eager f-string that needs this extra guard.)

issue_77_fstring_eager_eval.py
import logging
import io
import time

log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
logger = logging.getLogger("perf")
logger.addHandler(handler)
logger.setLevel(logging.WARNING)  # DEBUG-level messages are disabled

call_count = 0

def expensive_summary(data):
    global call_count
    call_count += 1  # stands in for genuinely expensive formatting work
    return f"summary of {len(data)} records: {sum(data)}"

data = list(range(1000))

# BUG: an f-string is built EAGERLY, every time this line runs, even
# though logger.debug() will immediately throw the result away because
# the logger is set to WARNING
logger.debug(f"debug info: {expensive_summary(data)}")
print(f"expensive_summary() was called even though nothing was logged: {call_count} time(s)")

call_count = 0
# FIX: pass the expensive part as a lazy argument -- logging only calls
# str() on it (which triggers the % formatting) if the message will
# actually be emitted
logger.debug("debug info: %s", expensive_summary(data) if logger.isEnabledFor(logging.DEBUG) else None)
print(f"with an isEnabledFor() guard, expensive_summary() was called: {call_count} time(s)")
actual output (Python 3.14.4)
expensive_summary() was called even though nothing was logged: 1 time(s)
with an isEnabledFor() guard, expensive_summary() was called: 0 time(s)
#78

A log file that grows forever and eventually fills the disk

Symptom

A service that's been running for weeks suddenly starts throwing disk-related errors on completely unrelated operations — writing a temp file, saving an upload — all because the disk itself is full.

Root cause

A plain logging.FileHandler opens one file and keeps appending to it, with no concept of a size limit — there's nothing built into it that ever rotates, truncates, or deletes old content. For a service that logs continuously over weeks or months of uptime, that one file grows without bound until it eventually consumes all available disk space, at which point every disk-writing operation on the whole machine starts failing, not just logging.

Fix

Use logging.handlers.RotatingFileHandler (or TimedRotatingFileHandler) instead of a plain FileHandler — it automatically rotates to a new file once the current one hits a size limit, and deletes the oldest backups once a configured number of backups is exceeded, capping total disk usage.

issue_78_unbounded_log_growth.py
import logging
import os

log_path = "/tmp/ch26_app.log"
if os.path.exists(log_path):
    os.remove(log_path)

logger = logging.getLogger("noisy")
logger.setLevel(logging.INFO)
# BUG: a plain FileHandler never rotates or caps the file -- it just
# keeps appending forever, until disk fills up
handler = logging.FileHandler(log_path)
logger.addHandler(handler)

for i in range(5000):
    logger.info(f"processed item {i}" * 3)  # simulate a somewhat verbose line

handler.flush()
size_bytes = os.path.getsize(log_path)
print(f"log file size after 5,000 lines: {size_bytes:,} bytes")
print("a plain FileHandler has no size cap -- this keeps growing indefinitely,")
print("which is exactly how a busy service fills its disk over weeks of uptime")

os.remove(log_path)
actual output (Python 3.14.4)
log file size after 5,000 lines: 286,670 bytes
a plain FileHandler has no size cap -- this keeps growing indefinitely,
which is exactly how a busy service fills its disk over weeks of uptime

Swapping in RotatingFileHandler(log_path, maxBytes=50_000, backupCount=3) for the exact same 5,000 log calls caps total disk usage at roughly 4 files of 50KB each, automatically discarding anything older than the 3 most recent backups — instead of one file that would otherwise keep growing without limit.

#79

A silently swallowed exception with no log line at all

Symptom

A customer calls support to say they never received an order confirmation email. There is absolutely nothing in any log, anywhere, that mentions that customer, that order, or any failure at all.

Root cause

This is issue #3's bare except: pattern taken to its most damaging extreme: except Exception: pass doesn't just catch too broadly — it produces zero record of the failure ever happening. Even a badly written log line beats no log line at all; with nothing logged, there is no starting point from which to even begin investigating, because there's no evidence the failure occurred in the first place.

Fix

Never write a bare except: pass (or except Exception: pass) in production code — at an absolute minimum, log the exception (with logger.exception(), per issue #76) even in a code path that's deliberately designed to continue past a failure, so there's a permanent record that something went wrong, even if the immediate decision is not to stop and surface it to the caller.

issue_79_exception_swallowed_no_log.py
def send_notification(user_id, message):
    if user_id == "user-999":
        raise ConnectionError("notification service unreachable")
    return "sent"

def notify_all(user_ids, message):
    sent = 0
    for uid in user_ids:
        try:
            send_notification(uid, message)
            sent += 1
        except Exception:
            pass  # BUG: completely silent -- not even a log line, nothing
    return sent

result = notify_all(["user-1", "user-999", "user-3"], "Your order shipped!")
print(f"notify_all() reports {result} of 3 notifications sent")
print("one silently failed -- there is NO record anywhere that it happened,")
print("no log line, no metric, nothing an on-call engineer could ever find")
actual output (Python 3.14.4)
notify_all() reports 2 of 3 notifications sent
one silently failed -- there is NO record anywhere that it happened,
no log line, no metric, nothing an on-call engineer could ever find

The function's own return value (2 out of 3) is the only hint anything went wrong — and only if the caller happens to check it and knows to compare it against the number of users passed in. Nothing forces that comparison to happen.

#80

Unstructured log messages that can't be queried at scale

Symptom

Answering "how many orders over $500 failed last week" requires someone to write a fragile regular expression against raw log text, rather than a simple, direct query.

Root cause

A free-form log message like f"Order {order_id} for customer {customer_id}: ${amount} - {status}" is easy for a human to read in isolation, but a log aggregator has no idea that the second number is a dollar amount or that the last word is a status — to it, it's just an unstructured string. Extracting any specific field back out means writing a regex that has to be updated every time the message's wording changes even slightly.

Fix

Log structured data — typically JSON — so each field is explicitly named and typed: {"order_id": ..., "amount": ..., "status": ...}. Nearly every modern log aggregator can index structured fields directly, turning "how many failed orders over $500" from a regex-writing exercise into a straightforward filter.

issue_80_unstructured_vs_structured_log.py
import logging
import io
import json

log_stream = io.StringIO()
handler = logging.StreamHandler(log_stream)
handler.setFormatter(logging.Formatter("%(message)s"))
logger = logging.getLogger("orders_unstructured")
logger.addHandler(handler)
logger.setLevel(logging.INFO)

def log_order_unstructured(order_id, customer_id, amount, status):
    # BUG: a free-form string -- easy to write, hard to query at scale.
    # Finding "every failed order over $500" means regex-parsing this text.
    logger.info(f"Order {order_id} for customer {customer_id}: ${amount} - {status}")

log_order_unstructured("ord-1", "cust-9", 750, "failed")

print("--- unstructured ---")
print(log_stream.getvalue())

log_stream2 = io.StringIO()
handler2 = logging.StreamHandler(log_stream2)
handler2.setFormatter(logging.Formatter("%(message)s"))
logger2 = logging.getLogger("orders_structured")
logger2.addHandler(handler2)
logger2.setLevel(logging.INFO)

def log_order_structured(order_id, customer_id, amount, status):
    # FIX: a structured (JSON) log line -- trivially queryable by any log
    # aggregator: "amount > 500 AND status = failed", no regex required
    logger2.info(json.dumps({
        "order_id": order_id,
        "customer_id": customer_id,
        "amount": amount,
        "status": status,
    }))

log_order_structured("ord-1", "cust-9", 750, "failed")

print("--- structured (JSON) ---")
print(log_stream2.getvalue())
actual output (Python 3.14.4)
--- unstructured ---
Order ord-1 for customer cust-9: $750 - failed

--- structured (JSON) ---
{"order_id": "ord-1", "customer_id": "cust-9", "amount": 750, "status": "failed"}

Thought process: structured logging is a decision that pays off precisely when it matters most — during an incident, under time pressure, when someone needs a specific answer from thousands of log lines fast. Its cost (writing json.dumps({...}) instead of an f-string) is trivial and paid once; its benefit compounds every single time anyone needs to query the logs afterward.

Write the prompt you'd give an AI assistant to build this:

Show a strong version of this prompt
Write a Python function log_order_event(logger, order_id, customer_id, amount, status) that logs order events as structured JSON (using json.dumps on a dict with named fields: order_id, customer_id, amount, status) rather than as an f-string message. Explain, with a concrete example query, why structured JSON logs are easier for a log aggregator (like Elasticsearch or CloudWatch Logs Insights) to filter and query than free-form text messages.
Quick recap
  • Nearly every bug in this category shares one theme: the evidence that would have explained an incident was never captured, either because it was never logged at all (issues #71, #79) or because it was logged in a form that turned out to be useless later (issues #72, #76, #80).
  • Logging a caught exception is not the same as handling it (issue #75) — a caller or downstream system still needs to know the operation failed, through a return value or a re-raised exception, not just through a log line a human might eventually read.
  • Good observability is mostly about anticipating the question someone will ask during an incident (which order, which customer, did this even run) and making sure the logs can already answer it, rather than trying to add the right log line after the incident has already happened.
In the Real World (Category 8)

Points to Remember

← All Chapters Take the Quiz →