Find the bug · #22 · Types and comparisons Medium Python
Prices vanish after a restart
The app caches prices to disk, and after a restart every price lookup comes back empty.
On this page
The report
The app saves product prices to a cache file so it can restart without fetching them all again. After every restart, each price lookup comes back empty, and the shop shows “Price unavailable” until the cache refills.
The code
Read it first: what should it do? Then click the line where you think the bug is.
import json
def to_cache(prices):
"""Saves {product_id: price} so the app can restart without refetching."""
return json.dumps(prices)
def from_cache(text):
return json.loads(text)Read it, then pick a line.
In JSON, what type are the keys of an object, always?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
prices = {101: 499, 102: 1299}
restored = from_cache(to_cache(prices))
print(prices.get(101))
print(restored.get(101))It prints
499 None
It should print
499 499
Show the answer: the bug, the fix, and how you’d find it
The bug (line 8)
JSON object keys are always strings. json.dumps quietly turns the int keys 101 and 102 into "101" and "102", and line 8 loads them back as strings. Looking up a price by its int product id then finds nothing. Convert the keys back when loading.
The fix
5 return json.dumps(prices)6 7def from_cache(text):8 return json.loads(text)8 return {int(k): v for k, v in json.loads(text).items()}How you’d find it
- Reproduce with a round trip: save, load, look up 101. You get
None. - Print the restored dictionary:
{"101": 499, "102": 1299}. The keys came back as strings. - That’s JSON itself: its object keys can only be strings. The fix belongs where the data is loaded.
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.
prices = {101: 499, 102: 1299}
assert from_cache(to_cache(prices)) == pricesWhere else this bites
- JavaScript objects have string keys too; a
Mapkeeps1and"1"apart. - Query strings and form fields are always strings until you convert them.