Python traps 2 · Chapter 2 of 16
Falsy values and or defaults
Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.
- Part: Names
- 3 tasks
- Python
- Free chapter
Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.
The lesson
By the end of this case
You can tell when x or default throws away a real value such as 0, make it happen on purpose with one account, fix it with an is None test that keeps 0 and still defaults a missing or null value, and guard it with a test that checks every edge.
The ticket
DD-515: Free-delivery offices charged ₹30 on every lunch. Assigned to you by Kunal. Priority: high. Since: the corporate accounts went live.
Rafiq, in the accounts group at 4:10 pm: "Lotus Park's contract says free delivery, and every one of their lunches this month has ₹30 of delivery on it. Their admin sent me the contract with the line highlighted. And D3122 is worse: the customer took the rotis off in the app, and we billed the rotis anyway."
The billing job's log for three of this week's lunches:
billing: D3121 Lotus Park offices fee 30 total 250
billing: D3122 Lotus Park offices fee 30 total 195
billing: D3123 Harbour Lane studio fee 30 total 230
Kunal: "The accounts JSON has a delivery_fee for each corporate account, and Lotus Park's is 0. Harbour Lane has none, so ₹30 is right for them. The app sends a qty of 0 when a dish is taken off, and leaves it out when it is 1. So the zeros are going in and something turns them into the default. Reproduce it, fix fees.py, and make sure it never comes back."
or picks the first truthy value
a or b does not ask "is a missing?". It asks "is a truthy?", and gives a if it is, b if not. 0, "", [], None and False are all falsy:
print(0 or 10)
print("" or "Guest")
print([] or ["roti"])
print(None or 10)
10
Guest
['roti']
10
So x or default is a fine default only when no falsy value can be a real answer. A rider's tip of ₹0 is a real answer:
def rider_tip(order):
return order.get("tip") or 10
print(rider_tip({"id": "D3150"}))
print(rider_tip({"id": "D3151", "tip": 25}))
print(rider_tip({"id": "D3152", "tip": 0}))
10
25
10
Nothing complains: the function returns a number every time, and every test with a normal tip passes.
Missing, null and zero
JSON has three ways to say less: the key is not there, the key is there with null, or the key is there with 0. json.loads turns null into None, and a key that holds None is not missing, so a .get default does not cover it:
import json
order = json.loads('{"id": "D3153", "tip": null}')
print(order)
print(order.get("tip", 10))
print(order.get("tip", 10) + 40)
{'id': 'D3153', 'tip': None}
None
Traceback (most recent call last):
File "/tmp/w1/c2c.py", line 6, in <module>
print(order.get("tip", 10) + 40)
~~~~~~~~~~~~~~~~~~~~~^~~~
TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'
The fix that covers all three asks the real question, "is it None?":
def rider_tip(order):
tip = order.get("tip")
if tip is None:
return 10
return tip
For {"id": "D3150"}, a tip of 0 and a tip of None it gives 10, 0 and 10. Use is None, not == None: None is a single object.
Making it happen on purpose
Your reproduce() makes the ticket's account, with a delivery_fee of 0, and returns what delivery_fee gives for it. The check runs it beside the original fees.py (30) and beside a fixed one (0).
Testing every edge
A guard for a default must try each edge: a normal value, 0, missing and null. @pytest.mark.parametrize runs one test once per row:
@pytest.mark.parametrize("text, tip", [
('{"id": "D3150"}', 10),
('{"id": "D3151", "tip": 25}', 25),
('{"id": "D3152", "tip": 0}', 0),
('{"id": "D3153", "tip": null}', 10),
])
def test_rider_tip(text, tip):
assert rider_tip(json.loads(text)) == tip
Beside the or version, pytest names the row that failed (trimmed):
FAILED test_tips.py::test_rider_tip[{"id": "D3152", "tip": 0}-0] - assert 10 ...
========================= 1 failed, 3 passed in 0.03s ==========================
Beside the .get("tip", 10) version, the null row fails instead. A test with only the 0 row would miss that one.
Your turn
Three tasks, one file each. In repro.py, charge the free-delivery account the default fee on purpose, and run it with python3 repro.py. In fees.py, fix the fee and the quantity. In test_fees.py, write the guard and run it with python3 -m pytest test_fees.py: the check runs it beside the original code, the fix and a wrong fix that uses a .get default. Then answer Kunal's interview question at the bottom of the case.
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: a free-delivery account pays ₹30
Write reproduce() in repro.py. Make the account from the ticket, the dict {"name": "Lotus Park offices", "delivery_fee": 0}, call delivery_fee from fees.py with it, and return what it gave.
The check runs your reproduce() twice: beside the original fees.py it must return 30 (the default fee, though the contract says 0), and beside a fixed fees.py it must return 0. So it must really call delivery_fee with that account: a repro that just returns 30 fails the second run. No real waiting and no input(): reproduce() must finish within 3 seconds.
- Task 2
fees.py: free delivery stays free
Fix fees.py. delivery_fee(account) returns the account's "delivery_fee" whenever it is a number, 0 included, and DEFAULT_FEE (30) only when "delivery_fee" is missing or null (None). bill_total(order, account) adds up each line's "price" times its "qty", where a qty that is missing or null counts as 1 and a qty of 0 counts as 0, then adds the delivery fee and returns the total.
Keep DEFAULT_FEE at 30, and keep the log line, billing: <order id> <account name> fee <fee> total <total>, printed once per bill. The check imports a fresh copy of your fees.py and uses its own accounts and orders, some read with json.loads, so a null arrives as None: a fix that keeps 0 but turns a null fee into None is as wrong as the bug.
- Task 3
test_fees.py: a test that would have caught it
Write a pytest file, test_fees.py, that would have caught this bug before Lotus Park paid for free delivery. The check runs your file three times: beside the original fees.py, where at least one test must fail; beside the fixed fees.py, where every test must pass; and beside a wrong fix that uses account.get("delivery_fee", 30), where at least one test must fail.
So test the edges, not only a normal fee: an account with a delivery_fee of 0 pays 0, and an account whose delivery_fee is null in the JSON pays the default, 30. No real waiting: each test must finish within 3 seconds.
What you will learn
- repro.py: a free-delivery account pays ₹30
- fees.py: free delivery stays free
- test_fees.py: a test that would have caught it
More in Names
Build "Falsy values and or defaults" yourself
Monsoon season at DabbaDrop brings a new pile of tickets from Kunal. 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.