Find the bug · #40 · Async Medium Python
Out-of-stock items still go in the cart
Since the stock check became async, out-of-stock items get added to carts anyway.
On this page
The report
The stock check became async when it moved to a separate service. Since then, out-of-stock items get added to carts anyway, and those orders fail at payment.
The code
Read it first: what should it do? Then click the line where you think the bug is.
import asyncio
async def in_stock(sku, stock):
await asyncio.sleep(0) # stands in for the call to the stock service
return stock.get(sku, 0) > 0
async def add_to_cart(sku, cart, stock):
if in_stock(sku, stock):
cart.append(sku)
return cartRead it, then pick a line.
What does calling an async function return, if you don’t await it?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
stock = {"pen": 3, "ink": 0}
print(asyncio.run(add_to_cart("ink", [], stock)))It prints
['ink']
It should print
[]
Show the answer: the bug, the fix, and how you’d find it
The bug (line 8)
Line 8 calls in_stock(...) without await. Calling an async function doesn’t run it: it returns a coroutine object, and any object is truthy, so the check always passes. Python does warn, “coroutine was never awaited”, but only in the logs. Await it.
The fix
5 return stock.get(sku, 0) > 06 7async def add_to_cart(sku, cart, stock):8 if in_stock(sku, stock):8 if await in_stock(sku, stock):9 cart.append(sku)10 return cartHow you’d find it
- Reproduce with an item that has 0 in stock: it still goes in the cart.
- Print what the condition gets:
<coroutine object in_stock …>. That’s always truthy. - Search the logs for “RuntimeWarning: coroutine ... was never awaited”: Python points straight at this line.
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 asyncio.run(add_to_cart("ink", [], {"ink": 0})) == []
assert asyncio.run(add_to_cart("pen", [], {"pen": 2})) == ["pen"]Where else this bites
- The JavaScript version:
if (isInStock())on a promise (see “Every account looks deactivated”). - Any check that became async in a refactor while its callers didn’t change.