Python traps · Chapter 1 of 16
Mutable default arguments
Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Everyday traps
- 3 tasks
- Python
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
Why you need this
Nothing here is an error. append on a list is fine, the function returns a list, and the first call after a restart is even right. The default lives as long as the function, so a restart "fixes" it and the next calls bring it back: exactly Bhavna's pattern. A linter knows the trap. Ruff, in the lab, says (trimmed):
$ ruff check --select B006 route.py
B006 Do not use mutable data structures for argument defaults
--> route.py:1:28
The usual fix is a default that cannot change, None, and a new list made inside the function when the caller gave none:
def plan_route(area, stops=None):
if stops is None:
stops = []
stops.append(area)
return stops
['Andheri']
['Bandra']The lesson
By the end of this case
You can tell a mutable default argument from its symptoms, make it happen on purpose in a fresh Python, fix it with a None default, and pin it down with a pytest test that fails on the bug and passes on the fix.
The ticket
DD-412: Tiffins packed with dishes nobody ordered. Assigned to you by Kunal. Priority: high. Since: Monday's release.
Bhavna, in the kitchen group at 1:15 pm: "The lunch labels have gone mad. D2043 was Rohan in Andheri, two rotis, ₹30. The label said dal tadka, veg pulao, roti, roti, so the kitchen packed all of it. Every label has the one before it inside. After the 11 am restart it was fine for a few orders, then it started again."
The kitchen printer's log for the first orders after the restart, with the order service's lines:
11:02:14 orders order D2041: added dal-tadka
11:02:14 printer D2041 C014: dal-tadka
11:02:51 orders order D2042: added veg-pulao
11:02:51 printer D2042 C022: dal-tadka, veg-pulao
11:03:30 orders order D2043: added roti
11:03:30 orders order D2043: added roti
11:03:30 printer D2043 C031: dal-tadka, veg-pulao, roti, roti
Kunal: "Monday's release changed one thing in orders.py: the website now starts every new tiffin with new_order, and repeat orders pass in last time's dishes. Look at the labels: each order carries every order since the restart. Something lives as long as the process does. Reproduce it first, then fix it, then make sure it can never come back. You are in orders.py."
Defaults are made once
Python works out a default value once, when the def line runs, and keeps that object on the function. Every call that leaves the argument out gets the same object. With a number or a string that is harmless. With a list, it is one list for every call. Here is a rider's route planner of the same kind:
def plan_route(area, stops=[]):
stops.append(area)
return stops
print(plan_route("Andheri"))
print(plan_route("Bandra"))
print(plan_route.__defaults__)
['Andheri']
['Andheri', 'Bandra']
(['Andheri', 'Bandra'],)
__defaults__ is where the function keeps its default values: the one list, with both calls' stops in it. In a fresh run, two calls even hand back the very same object:
first = plan_route("Dadar")
second = plan_route("Powai")
print(first is second)
print(first)
True
['Dadar', 'Powai']
Making it happen on purpose
A bug you can only see in production is a bug you cannot fix with confidence. So you reproduce it first, every time: here that means calling the code twice in a row in a fresh Python, the way the website does after a restart. Your repro is a function, reproduce(), that runs the ticket's steps and returns what the code gave. It never asserts and never decides the answer itself.
The check runs your reproduce() in a fresh python3 twice: once beside the original orders.py, where it must give the bug's value, and once beside a fixed one, where it must give the healthy value. A repro that returns the answer without calling the code fails the second run.
A test that would have caught it
A guard test turns the repro into something that runs before every release. A pytest test is a function whose name starts with test_, and assert checks a value. For the route planner:
# test_routes.py
from routes import plan_route
def test_each_rider_gets_a_fresh_route():
plan_route("Andheri")
assert plan_route("Bandra") == ["Bandra"]
Beside the buggy planner it fails (trimmed):
$ python3 -m pytest test_routes.py
> assert plan_route("Bandra") == ["Bandra"]
E AssertionError: assert ['Andheri', 'Bandra'] == ['Bandra']
FAILED test_routes.py::test_each_rider_gets_a_fresh_route - AssertionError: a...
============================== 1 failed in 0.02s ===============================
Beside the fixed one it passes (trimmed):
test_routes.py . [100%]
============================== 1 passed in 0.01s ===============================
A good guard fails on the bug and passes on the fix. A test that fails on everything proves nothing, and so does one that only checks one side: a "fix" that empties the shared list whenever a new order starts makes the new order look right, while the earlier order loses its dishes.
Your turn
Three tasks, one file each. In repro.py, put one order's dal in the next order on purpose, and run it with python3 repro.py in the case's folder. In orders.py, fix the bug. In test_orders.py, write the guard: the check runs it beside the original code, the fix and a wrong fix that empties the shared list. Then answer Kunal's interview question at the bottom of the case, in your own words.
What you build: 3 tasks
Each task has tests. You write the code in the lab's editor and press Check.
- Task 1
repro.py: one order's dal in the next order's tiffin
Write reproduce() in repro.py. Start two orders with new_order(order_id, customer_id) from orders.py, each without any dishes (any ids you like), add "dal-tadka" to the first one with add_dish, and return the second order's list of dishes, order["dishes"].
The check runs your reproduce() twice: beside the original orders.py it must return ['dal-tadka'] (the first order's dish turned up in the second), and beside a fixed orders.py it must return []. So it must really make the two orders and add the dish. No real waiting and no input(): reproduce() must finish within 3 seconds.
- Task 2
orders.py: every tiffin starts empty
Fix new_order(order_id, customer_id, dishes) in orders.py. Called without dishes, it must start the order with an empty list of dishes every time, however many orders came before it and whatever was added to them. Called with a list of dishes (a repeat order), it keeps that list. Dishes added to one order with add_dish must never show up in another order.
new_order still returns {"id": ..., "customer": ..., "dishes": [...]}. Keep add_dish, label and add_dish's log line (order <id>: added <dish>) as they are. The check imports a fresh copy of your orders.py and uses its own orders, not D2041, and a fix that empties the list when the next order starts is as wrong as the bug: the earlier order loses its dishes.
- Task 3
test_orders.py: a test that would have caught it
Write a pytest file, test_orders.py, that would have caught this bug before it reached the kitchen. The check runs your file three times: beside the original orders.py, where at least one test must fail; beside the fixed orders.py, where every test must pass; and beside a wrong fix that empties the shared list each time a new order starts, where at least one test must fail.
So test both sides: an order started after another order got a dish has no dishes, and the earlier order still has its own dish after the next one starts. No real waiting: each test must finish within 3 seconds.
What you will learn
- repro.py: one order's dal in the next order's tiffin
- orders.py: every tiffin starts empty
- test_orders.py: a test that would have caught it
More in Everyday traps
Build "Mutable default arguments" yourself
DabbaDrop runs on Python, and Kunal, its senior developer, keeps assigning you tickets. Each is a real trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.