The Mutable Default Trap — Python Bug Hunt
Inspired by Python's most famous footgun — the one in every interview and, somehow, still in every codebase: a mutable default argument is created once and…
- Language: Python
- Layer: Backend
- Difficulty: Easy
- Concepts: Python Gotchas, State
- Modelled on: Python footguns
- Visible tests: fresh calls get fresh carts; explicit carts still accumulate
- Reward: 50 XP for a complete fix
Incident
- Severity: SEV-2 (priority: High (data bleed!))
- Ticket: BUG-DEF-ARG
- Reported by: checkout
- Time to fix: 10 minutes, the target for an easy incident
Failing checks on the shipped build
- fresh calls get fresh carts — customer A's cart: expected ["headphones"] but got ["headphones", "keyboard"]
How to work this incident
- Read the report: write down the expected behaviour and the actual one in a sentence each.
- Reproduce it: run the visible tests and find the failing check that matches the report.
- Read the logs and the failing checks for the first value that is wrong — the earliest wrong value is nearer the cause than the loudest error.
- Follow the request through the handler, the validation and the service it calls; find the first step whose output disagrees with the report.
- Fix the cause rather than the symptom, run the visible tests again, and submit against the hidden ones — then write the root cause down.
Briefing
Inspired by Python's most famous footgun — the one in every interview and, somehow, still in every codebase: a mutable default argument is created once and shared across every call. Two users' shopping carts become one.
carts.py: def add_item(item, cart=[]). You already know.
Bug report
BUG-DEF-ARG · Priority: High (data bleed!) · Reported by: checkout
add_item(item, cart=None) -> the cart with the item appended:
- calls WITHOUT a cart get a FRESH empty cart every time
- calls with an explicit cart append to that cart
Observed: customer B's brand-new cart already contains customer A's items.
Logs
[cart] new session cart contents: ["A's headphones"] (?!)The code as shipped
src/shop/carts.py (editable)
# Cart operations.
def add_item(item, cart=[]):
cart.append(item)
return cart
Open the hunt to start the incident clock, edit the files, run the visible tests and submit against the hidden ones, then write the root cause down. More Python bug hunts.