#14 · Shared references

Find the bug · #14 · Shared references Easy Python

New carts already have items

Every new visitor should start with an empty cart, but new carts are already full.

On this page

The report

Bug report

Each new visitor should start with an empty cart. Instead, new carts already contain things other people added.

The code

Read it first: what should it do? Then click the line where you think the bug is.

PythonClick the line you think is wrong
def add_to_cart(item, cart=[]):
    """Adds item to cart; a new cart starts empty."""
    cart.append(item)
    return cart

Read it, then pick a line.

What it prints

Running it on a small example prints the output on the left. It should print the output on the right.

The example
print(add_to_cart("pen"))
print(add_to_cart("book"))

It prints

['pen']
['pen', 'book']

It should print

['pen']
['book']
Show the answer: the bug, the fix, and how you’d find it

The bug (line 1)

Line 1 uses a list as the default value of cart. Python creates that default list once, when the function is defined, and reuses it on every call. So every call without a cart appends to the same list, and items pile up across visitors. Default to None and make a new list inside.

The fix

1def add_to_cart(item, cart=[]):1def add_to_cart(item, cart=None):2    """Adds item to cart; a new cart starts empty."""3    if cart is None:4        cart = []3    cart.append(item)4    return cart

How you’d find it

  1. Reproduce: two calls with no cart. The second already contains the first one’s item.
  2. Right the first time, wrong the second: that’s state surviving between calls. The only thing shared between calls here is the default value.
  3. Confirm it: add_to_cart.__defaults__ shows the default list, and it grows after every call.

The test that catches it

It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.

first = add_to_cart("pen")
second = add_to_cart("book")
assert second == ["book"]
assert first == ["pen"]
assert add_to_cart("cap", ["bag"]) == ["bag", "cap"]

Where else this bites

  • The same with {} or set() as a default.
  • JavaScript evaluates default parameters on every call, so it doesn’t have this one.
Your progress stays on this device.