Full round 5 of 5

Full round 5 of 5 Hard Python

Stock import

A stock importer in three files: its report keeps listing old problems. Then suppliers’ new file format, then a lookup that scans everything.

60:00

The real round is about an hour. Start the clock, do all four tasks out loud, and open an answer only when you’ve finished that task.

On this page

The handover

The interviewer

“Suppliers upload stock files and we add the quantities to our products. importer.py runs an import, stockcsv.py reads the file, and repo.py stands in for the products table (it counts how many products it looks at). Ops have a complaint about the report.”

The code

Read all 3 files before anything else. For each one, say in a sentence what it does, then follow one request through them.

3 files

importer.py

from stockcsv import parse

def import_stock(text, repo, unknown=[]):
    """Adds each row's quantity to its product's stock. Returns the SKUs it didn't know."""
    for sku, qty in parse(text):
        product = repo.find_by_sku(sku)
        if product is None:
            unknown.append(sku)
            continue
        product["stock"] += qty
    return unknown

stockcsv.py

import csv
import io

def parse(text):
    """The rows of a stock file, one 'sku,qty' per line, as (sku, qty)."""
    rows = []
    for record in csv.reader(io.StringIO(text)):
        if not record:
            continue
        sku, qty = record
        rows.append((sku.strip(), int(qty)))
    return rows

repo.py

class Repo:
    """A stand-in for the products table. It counts how many products it looks at."""

    def __init__(self, products):
        self.products = products
        self.looked_at = 0

    def find_by_sku(self, sku):
        for p in self.products:
            self.looked_at += 1
            if p["sku"] == sku:
                return p
        return None

    def all(self):
        self.looked_at += len(self.products)
        return list(self.products)

Read every file first. After the report below, come back and click the line that causes it.

1Fix the bug

Bug report

After each import, the summary lists SKUs we don’t recognise. Ops say it lists SKUs from earlier imports, even ones that were fixed weeks ago, and the list only ever grows until the service restarts.

Reproduce it

This example shows the report happening. Before reading on, work out why it prints what it does.

The example
from repo import Repo
from importer import import_stock
repo = Repo([{"sku": "TEE", "stock": 5}, {"sku": "CAP", "stock": 2}])
print(import_stock("TEE,10\nHAT,3", repo))
print(import_stock("CAP,4", repo))

It prints

['HAT']
['HAT']

It should print

['HAT']
[]

Your hypothesis

Say it out loud, or write it here, before you hunt for the line: which file, what’s going wrong, and what you’d check to prove it.

It stays on this device.
Show the fix: the cause, the change and the test

The cause (importer.py, line 3)

importer.py line 3 gives unknown a default of []. Python creates that list once, when the function is defined, so every import that doesn’t pass its own list appends to the same one: old unknown SKUs pile up in every later report until the process restarts. Default to None and make a new list inside.

The fix

importer.py

1from stockcsv import parse2 3def import_stock(text, repo, unknown=[]):3def import_stock(text, repo, unknown=None):4    """Adds each row's quantity to its product's stock. Returns the SKUs it didn't know."""5    unknown = [] if unknown is None else unknown5    for sku, qty in parse(text):6        product = repo.find_by_sku(sku)7        if product is None:

The test that proves it

It fails on the original code and passes once it’s fixed. Keep it, so the bug can’t come back.

from repo import Repo
from importer import import_stock
repo = Repo([{"sku": "A", "stock": 0}])
assert import_stock("B,1", repo) == ["B"]
assert import_stock("A,2", repo) == []
assert repo.products[0]["stock"] == 2

2Check the AI

The assistant in the side panel is allowed. Before you found the cause, you asked it about the report. Would you act on its answer?

You

Why does the import report list SKUs from earlier imports?

Assistant

csv.reader keeps an internal buffer when you reuse the same StringIO between imports. Create a new StringIO for each import, or call .seek(0) before reading, and the old rows won’t come back.

Show what’s wrong with its answer

parse already makes a new StringIO on every call, so there’s nothing being reused, and the old entries aren’t rows, they’re SKUs in the returned list. Print id() of the returned list after two imports: it’s the same list both times. The answer sounds technical but doesn’t match the code; ask the assistant to point to the exact line it means, and check it.

3Add a feature

The interviewer

Suppliers now send files with a header row, and not always in the same column order: name,qty,sku from one, sku,qty from another. Use the header when there is one (a first row that contains sku). Files without a header are still sku,qty.

Start from your fixed code. Say the feature back as a contract, ask about its edges, then build it with a test.

Show one way to build it

The approach

Read the columns’ positions from the header instead of assuming them, and keep the old format working: existing suppliers shouldn’t have to change anything. Extra columns (like name) are ignored.

The change

stockcsv.py

2import io3 4def parse(text):5    """The rows of a stock file, one 'sku,qty' per line, as (sku, qty)."""6    rows = []7    for record in csv.reader(io.StringIO(text)):8        if not record:9            continue10        sku, qty = record11        rows.append((sku.strip(), int(qty)))12    return rows5    """The rows of a stock file as (sku, qty). A first row that names the columns (one of them6    'sku') is a header and decides the order; without one, each line is 'sku,qty'."""7    records = [r for r in csv.reader(io.StringIO(text)) if r]8    if not records:9        return []10    header = [h.strip().lower() for h in records[0]]11    if "sku" in header:12        s, q = header.index("sku"), header.index("qty")13        body = records[1:]14    else:15        s, q = 0, 116        body = records17    return [(r[s].strip(), int(r[q])) for r in body]

The test

It fails before the feature and passes after; the bug’s test still passes too.

from stockcsv import parse
assert parse("name,qty,sku\nT-shirt,10,TEE\nCap,3,CAP") == [("TEE", 10), ("CAP", 3)]
assert parse("TEE,4") == [("TEE", 4)]
assert parse("") == []

4Make it faster

The interviewer

find_by_sku scans the whole product list for every row. Importing 10,000 rows against 50,000 products looks at up to 500 million products, and big imports time out. Make an import look at each product about once.

First count what it does too much of. Then change it without changing what it returns, and say what the change costs.

Show the speed-up and why it works

Why it’s slow, and the fix

A lookup inside a loop made the import O(rows × products). Building a dictionary from SKU to product once (one pass over the products) makes each row’s lookup O(1), so the whole import is O(rows + products). In a real database the same fix is one query for all the SKUs in the file, or an index on sku.

The change

importer.py

3def import_stock(text, repo, unknown=None):4    """Adds each row's quantity to its product's stock. Returns the SKUs it didn't know."""5    unknown = [] if unknown is None else unknown6    by_sku = {p["sku"]: p for p in repo.all()}6    for sku, qty in parse(text):7        product = repo.find_by_sku(sku)8        product = by_sku.get(sku)8        if product is None:9            unknown.append(sku)10            continue

The test

It fails on the code before the speed-up and passes after. Every earlier test still passes, so the behaviour didn’t change.

from repo import Repo
from importer import import_stock
products = [{"sku": "P" + str(i), "stock": 0} for i in range(2000)]
repo = Repo(products)
import_stock("\n".join("P" + str(i) + ",1" for i in range(0, 2000, 2)), repo)
assert repo.looked_at <= 2 * len(products), repo.looked_at
assert products[1998]["stock"] == 1

Sum it up

Score yourself

Tick what you really did. Interviewers score the process, so be honest: anything unticked is what to practise in the next round.

0 of 8

Your progress stays on this device.