Start learning free

LESSON 164 OF 188 · BACKEND: BACKEND WITH AI

A Shared Default

Practice

The shop keeps each customer's cart in the dictionary carts, and its routes make new carts with make_cart: {"owner": "ana", "items": []}. The items parameter lets restore_cart bring back a saved cart; without it, a cart starts empty. An AI assistant wrote it like this:

def make_cart(owner, items=[]):
    return {"owner": owner, "items": items}

Then Ben added a pen and found Ana's mug in his cart. Python makes a default value once, when it runs the def line, not at each call. So every cart made without items gets that same one list, and what one customer adds, every customer sees. This is a shared default. A smaller example:

def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags

print(add_tag("new"))    # ['new']
print(add_tag("sale"))   # ['new', 'sale']: the same list again

The fix: use None as the default. None can't be changed, so sharing it is harmless. Then, inside the function, make a new empty list when the value is None: lines inside a function run at every call, so every call gets a list of its own. A list that was passed in, like a restored cart, is kept as it is.

Your rewrite must give these answers:

POST /carts/ana/items  {"product": "Mug"}   →  201  {"owner": "ana", "items": ["Mug"]}
POST /carts/ben/items  {"product": "Pen"}   →  201  {"owner": "ben", "items": ["Pen"]}
POST /carts/ana/items  {"product": "Lamp"}  →  201  {"owner": "ana", "items": ["Mug", "Lamp"]}
GET  /carts/ben                             →  200  {"owner": "ben", "items": ["Pen"]}
GET  /carts/eva                             →  200  {"owner": "eva", "items": []}
PUT  /carts/chloe  {"items": ["Plant", "Teapot"]}  →  200  {"owner": "chloe", "items": ["Plant", "Teapot"]}

Your task: rewrite make_cart so a cart made without items gets a new empty list of its own, and a cart made with items keeps that list.


Assignment
Follow the Coding Tutorial to rewrite make_cart with None as the default and a new list made inside the function.


Hint
The new list must be made inside the function, below the def line, so it runs at every call. Check with items is None. When AI code has a list or a dictionary as a default value, ask whether every call shares it.


STEP 1 OF 4
    Ctrl + Enter to check