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

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 edit the files, run the visible tests and submit against the hidden ones. More Python bug hunts.