Find the bug · #8 · Empty and null Easy Python
Some profiles won’t open
Users who signed up before addresses existed can’t open their profile page.
On this page
The report
Users who signed up before the app asked for addresses can’t open their profile page: it shows an error instead.
The code
Read it first: what should it do? Then click the line where you think the bug is.
def shipping_city(user):
"""The city to show on the profile page, or 'Not set'."""
city = user["address"]["city"]
return city if city else "Not set"Read it, then pick a line.
The function promises “Not set” when there’s no city. What if there’s no address at all?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
print(shipping_city({"name": "Asha", "address": {"city": "Pune"}}))
try:
print(shipping_city({"name": "Ravi"}))
except Exception as e:
print(type(e).__name__, e)It prints
Pune KeyError 'address'
It should print
Pune Not set
Show the answer: the bug, the fix, and how you’d find it
The bug (line 3)
Line 3 reads user["address"]["city"]. Users who never added an address have no address key, so Python raises KeyError before the “Not set” fallback is ever reached. Optional data needs .get() with a default at each level.
The fix
1def shipping_city(user):2 """The city to show on the profile page, or 'Not set'."""3 city = user["address"]["city"]3 city = user.get("address", {}).get("city")4 return city if city else "Not set"How you’d find it
- Reproduce with the kind of user in the report: an old account with no address. It raises
KeyError: 'address'. - Read the traceback: it points at line 3, the double lookup. The fallback on line 4 handles an empty city, but the code crashes before getting there.
- Check the other shapes the data can take: no address, an empty address, an address with no city. Each needs to end up at “Not set”.
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.
assert shipping_city({"name": "Ravi"}) == "Not set"
assert shipping_city({"address": {}}) == "Not set"
assert shipping_city({"address": {"city": "Pune"}}) == "Pune"Where else this bites
- JavaScript’s
user.address.citythrows a TypeError the same way;user.address?.cityis the fix. - JSON from older app versions or third-party APIs often leaves fields out.