The interesting thing about this lab is not the answer, it is why there are three. Three symptoms — every receipt holding the same items, totals of Rp0, a daily till of Rp0 — look like one disease. The three layers are different, and each one has a different cure.
There is one theme, and it is the thing worth taking home: what are you changing, and what is that thing really? Every layer breaks because the author thought they were changing one object while they were changing another — or changing nothing at all.
Key takeaways
- Three layers, one theme: what you are changing, and what that thing actually is.
- A function's default value is computed once, so the list in its default is shared forever.
- Rebinding a local name does not change the contents of the dict the caller holds.
- A name assigned inside a function is local, unless you say outright that it belongs to the module.
- Fixing only layer 1 still leaves 4 of 6 checks red.
Measurements
There are six checks. Right-hand column: how many are still red.
| variant | red |
|---|---|
| initial state | 6 of 6 |
| layer 1 only | 4 of 6 |
| all three layers | 0 of 6 (green) |
The middle row is the one most people skip. Fixing the most famous layer still leaves 4 of 6 red, because the other two problems live somewhere else.
Layer 1 — a default value computed once
This is the layer everyone knows.
def pesanan_baru(meja, item=[]): # wrong
It looks reasonable: "if the caller sends no items, make a new empty list." What you cannot see:
a function's default value is computed once, when the function is first defined in memory, not
on every call. So that [] is not a fresh empty list per call — it is one single list, reused
forever. Every receipt shares it.
def pesanan_baru(meja, item=None): # right
if item is None:
item = []
return {"meja": meja, "item": item, "total": 0}
You do not have to take anyone's word for it; check it yourself:
kasir.pesanan_baru(1)["item"] is kasir.pesanan_baru(2)["item"] # must be False
You do not even need to measure the proof: pesanan_baru.__defaults__ holds that list literally.
Fill one receipt, then look at __defaults__ — the item you just added shows up there too, because
pesanan["item"] and the default value are the same object. Note also that pesanan_baru
itself never adds anything to that list. Some other function does the adding, and the list still
grows — because there is only one.
Layer 2 — changing a local name, not the value inside the dict
total = pesanan["total"] # copies the VALUE
total = total + harga * qty # only the local name changes
return pesanan # the receipt never finds out
total = pesanan["total"] makes a new name total that points at the same number. The next line
changes the number under that name — but pesanan still holds the old one. The local name dies when
the function returns.
pesanan["total"] = pesanan["total"] + harga * qty # right
The difference is subtle, but this is the core of it: what gets changed is the contents of the dict the caller holds. Rebinding a variable is not the same as changing the object you meant — the same name in two places is no guarantee of the same object.
Layer 3 — a name that belongs to the module, or one that belongs to the function
TOTAL_KAS = 0
def catat_penjualan(jumlah):
total = TOTAL_KAS # creates a new local name
total = total + jumlah # only the local one changes
return total # TOTAL_KAS is never touched
The original author stopped halfway: the intent was to add to TOTAL_KAS, but it was written
through another variable. As a result TOTAL_KAS stays zero forever. Had they written it directly,
without telling Python that the name belongs to the module:
def catat_penjualan(jumlah):
TOTAL_KAS = TOTAL_KAS + jumlah # UnboundLocalError
Python throws UnboundLocalError instead. The reason: the moment a name is assigned anywhere inside
a function, Python treats that name as local for the whole function. When it reads TOTAL_KAS
on the right-hand side, it does not yet consider it to exist. Ironically that error is the better
outcome, because it is visible. The original author avoided it, and that is what made the bug
silent.
def catat_penjualan(jumlah):
global TOTAL_KAS # right
TOTAL_KAS = TOTAL_KAS + jumlah
return TOTAL_KAS
global tells Python: the name TOTAL_KAS here refers to the module-level one, do not create a new
one in here.
Traps that are easy to fall into
item or [] instead of if item is None. Looks tighter and stays correct in this demo — but it
breaks as soon as a caller deliberately passes an empty list, because item or [] replaces it with
a new list, while the caller wanted that list filled.
Sprinkling .copy() everywhere so nothing overwrites anything. .copy() makes a new container,
not new contents. If the contents are themselves mutable, the copy still shares them with the
original. Before adding a copy, ask: do you want to separate the container or the contents?
Renaming variables so they "differ". Rename total to total_nota and the bug does not
disappear — it just changes name. The name was never the problem; the problem is that what changed
was a local name rather than the value inside the dict.
After all three are done
make check # target: 6 of 6
make demo # three tables, three receipts, matching what was ordered
At that point make demo stops complaining, and the three receipts become three different receipts:
table 1 kopi x2 totalling Rp30,000, table 3 teh x1 Rp8,000, table 5 roti x1 Rp12,000, daily till
Rp50,000.
And the question most worth carrying out of this lab is not "where is the bug", it is this one:
when you write x = ..., which object are you actually changing? Answer that correctly and the
three layers stop being a mystery.
Questions for you
- If
pesanan_barureceives a list from its caller, who should be responsible when that list changes afterwards — the sender, or the receiver? - Layers 2 and 3 look like two different bugs. Both can be reduced to one identical question. What is it?
- If
TOTAL_KASwere not a number but a dict, say{"kas": 0}, would layer 3 still need to tell Python that the name belongs to the module? Work it out on paper first, then in the terminal.