Advanced Python

Level recap · Advanced Python · Level 5

Robust code

Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.

What this level teaches: Clear errors, cleanup that always runs, patterns in text, and tests that catch bugs.

8 classesLevel exam

Take the level exam
  1. 1Your own kind of error

    A custom exception class.

    The idea

    Ticket PY-501 from the engineering lead: when stock runs out, the code raises a plain ValueError, and the shop page can't tell that apart from a typo in a form. Give stock problems their own error type.

    class StockError(Exception): pass makes a new kind of error. Code can raise it with a clear message, and the caller can catch exactly that kind with except StockError: while other errors still go up. Its message is the text you pass in.

    The code

    class StockError(Exception):
        pass
    def take(stock, name, qty):
        have = stock.get(name, 0)
        if have < qty:
            raise StockError(f"Only {have} left")
        stock[name] = have - qty
        return stock[name]
    print(take({"Toner": 5}, "Toner", 2))

    What it shows

    PASS Right on new test values
  2. 2Keep the first error: raise from

    Exception chaining.

    The idea

    Ticket PY-502 from support: when a quantity can't be read, users see invalid literal for int() with base 10. Show a clear message, and keep the original error for the developers.

    Inside except ValueError as error:, raise ValueError("Bad quantity: 'x'") from error raises a new, clear error and links the old one as its cause. The traceback shows both, and the new error's __cause__ is the old one.

    The code

    def parse_qty(text):
        try:
            return int(text)
        except ValueError as error:
            raise ValueError(f"Bad quantity: {text!r}") from error
    print(parse_qty("12"))

    What it shows

    PASS Right on new test values
  3. 3Clean up every time: context managers

    contextlib.contextmanager.

    The idea

    Ticket PY-503 from the audit team: every stock count must log start and end, even when the count fails half way. People keep forgetting the end.

    A context manager runs setup code before a with block and cleanup code after it. With @contextmanager, write a generator: the code before yield is the setup, and the code in finally: after it always runs, even when the block raises. The error still goes up to the caller.

    The code

    from contextlib import contextmanager
    @contextmanager
    def audit(log):
        log.append("start")
        try:
            yield log
        finally:
            log.append("end")
    log = []
    with audit(log):
        log.append("count shelf A")
    print(log)

    What it shows

    PASS Right on new test values
  4. 4Find patterns in text: re

    re.findall with a pattern.

    The idea

    Ticket PY-504 from customer care: emails mention order numbers like HS-1042 somewhere in the text. Pull every order number out, in order.

    A regular expression describes a pattern. In r"\bHS-\d{3,}\b", \d{3,} means three or more digits and \b means the edge of a word, so XHS-123 and HS-12 don't count. re.findall(pattern, text) gives back every match as a list. Write patterns as raw strings, r"...", so the backslashes stay as they are.

    The code

    import re
    def order_ids(text):
        return re.findall(r"\bHS-\d{3,}\b", text)
    print(order_ids("Re: HS-1042 and HS-12, see HS-2210."))

    What it shows

    PASS Right on new test values
  5. 5Read a log line with named groups

    re.match and (?P<name>...).

    The idea

    Ticket PY-505 from the platform team: turn each log line into fields the dashboard can use, and skip lines that don't fit the format.

    In a pattern, (?P<level>[A-Z]+) captures part of the match under a name. re.match(pattern, line) gives a match object or None, and match.groupdict() gives a dict of the named parts. One pattern reads the whole line, and anything that doesn't fit gives None.

    The code

    import re
    LINE = re.compile(r"^(?P<date>\d{4}-\d{2}-\d{2}) (?P<time>\d{2}:\d{2}:\d{2}) (?P<level>[A-Z]+) (?P<source>\w+): (?P<message>.+)$")
    def parse_log(line):
        match = LINE.match(line)
        return match.groupdict() if match else None
    print(parse_log("2026-06-01 10:00:01 ERROR db: timeout")["level"])

    What it shows

    PASS Right on new test values
  6. 6Write tests that catch bugs

    unittest.TestCase.

    The idea

    Ticket PY-506 from the engineering lead: order_total is about to be rewritten. Write the tests first, so a broken rewrite is caught before it ships.

    A test class inherits from unittest.TestCase. Each method whose name starts with test_ is one test. self.assertEqual(a, b) fails when the values differ, and with self.assertRaises(ValueError): fails when the code inside does not raise that error. Don't call unittest.main(): the grader runs your tests itself.

    The code

    import unittest
    def order_total(lines):
        total = 0
        for qty, price in lines:
            if qty < 0:
                raise ValueError("Negative quantity")
            total += qty * price
        return round(total, 2)
    class TestOrderTotal(unittest.TestCase):
        def test_total(self):
            self.assertEqual(order_total([(2, 1.5), (1, 4)]), 7)
        def test_empty(self):
            self.assertEqual(order_total([]), 0)
        def test_negative(self):
            with self.assertRaises(ValueError):
                order_total([(-1, 5)])
    print(unittest.defaultTestLoader.loadTestsFromTestCase(TestOrderTotal).countTestCases())

    What it shows

    PASS Right on new test values
  7. 7Take it to a real machine: a script you run from the terminal

    sys.argv and if __name__ == "__main__".

    The idea

    Ticket PY-508 from the IT lead: the order line should come from a script that runs on the office computer, from the terminal, not from a browser page.

    To run Python on your own computer, install Python 3 from python.org. On Windows, tick "Add python.exe to PATH" during the install. On a Mac or Linux it is often there already: open a terminal and type python3 --version. Save your code in a file such as report.py, then run python report.py Toner 3 (on a Mac or Linux, python3 report.py Toner 3).

    The code

    import sys
    def main(argv):
        if len(argv) != 2:
            return "Usage: python report.py ITEM QTY"
        item, qty = argv
        if not qty.isdigit():
            return "QTY must be a whole number."
        return f"Order {int(qty)} x {item}"
    if __name__ == "__main__":
        print(main(sys.argv[1:]))

    What it shows

    PASS Right on new test values
  8. 8On your own: load a price file safely

    Parse, skip and report bad lines, with no gold line.

    The idea

    Ticket PY-507 from purchasing: the supplier's price file has a few broken lines every week. Load every good line, and give a list of the bad line numbers so someone can fix them, instead of stopping at the first problem. Plan it: what makes a line bad, and what do you keep for each kind of line?

    In the code box, write a function load_prices(lines) where each line should be name,price. Give back a pair (prices, bad): prices is a dict from name to price as a float, and bad is the list of line numbers (counting from 1) that have no comma, a price that is not a number, or a price below 0. Then press Run my code.

    The code

    def load_prices(lines):
        prices, bad = {}, []
        for number, line in enumerate(lines, start=1):
            name, sep, price_text = line.partition(",")
            try:
                price = float(price_text)
            except ValueError:
                bad.append(number)
                continue
            if not sep or price < 0:
                bad.append(number)
                continue
            prices[name.strip()] = price
        return prices, bad

    What it shows

    PASS Right on new test values

Ready for the exam? The level exam is one real task that uses what this recap covers.

Take the level exam