Skip to content

08. Modules, packages and environments — Exercises

These exercises practice every idea of the modules, packages and environments lesson. They use the course datasets, the salesreport package of the lesson and the course environment.

How to work:

  1. Work in your course folder, the one that holds data/. Copy the salesreport/ folder of the lesson into it for the exercises that use the package.
  2. Copy the starter code into a script and replace each to-do comment with your code. Exercises with two files name each file in the block title; put them in a folder of their own.
  3. Run the script from the course folder, for example python exercise.py. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Many argparse exercises call parser.parse_args([...]) with a list. That runs the parser inside Python with the words you would type in the terminal, so you can test it without a terminal. To try the same parser in a terminal, call parser.parse_args() with no list and run python exercise.py data/sales.csv --top 3.

Warm-up

The first four order lines of data/sales.csv have the revenues 66.49, 14.99, 19.99 and 59.99. Write the code: import math as a whole module, statistics under the alias st and only the name Path from pathlib. Print the exact sum with math.fsum(), the mean with st.mean() and the stem and suffix of the path data/sales.csv.

Expected output
161.46
40.365
sales .csv
Starter
# TODO: three imports: math, statistics as st, Path from pathlib
revenues = [66.49, 14.99, 19.99, 59.99]
# TODO: print the sum, the mean, then the stem and suffix of data/sales.csv
Hint 1

Use three forms: import module, import module as alias and from module import name.

Hint 2

Path("data/sales.csv").stem is the file name without its suffix; .suffix is the part from the last dot.

Solution
import math
import statistics as st
from pathlib import Path
revenues = [66.49, 14.99, 19.99, 59.99]
path = Path("data/sales.csv")
print(math.fsum(revenues))
print(st.mean(revenues))
print(path.stem, path.suffix)
assert math.isclose(st.mean(revenues) * 4, math.fsum(revenues))
assert path.suffix == ".csv"
Output
161.46
40.365
sales .csv

How it works:

  1. import math binds the name math; you reach its functions with a dot.
  2. import statistics as st binds the same module object under the shorter name st.
  3. from pathlib import Path binds only Path, so you write Path(...) without a prefix.
  4. math.fsum() adds floats with extra care, so the sum shows no rounding error.

Alternative: from statistics import mean works too and is fine for one or two names. With many names from one module, import statistics as st keeps the source of each name visible.

M08-W02 · Predict the output: module names

Section titled “M08-W02 · Predict the output: module names”
Warm-up

Predict the output: write down what each line prints. Then run the code.

Acceptance criteria:

  • Write your prediction line by line, then run the code as a script.
  • Your prediction matches the Output in the solution.
Starter
import csv as table
import json
print(__name__)
print(json.__name__)
print(table.__name__)
print(table is __import__("csv"))
# TODO: write your prediction for each line before you run it
Hint 1

The file you run has a special name. An imported module keeps its real name, whatever name you bind it to.

Hint 2

__import__("csv") is the function that the import statement calls. It returns the module from sys.modules.

Solution
import csv as table
import json
print(__name__)
print(json.__name__)
print(table.__name__)
print(table is __import__("csv"))
assert __name__ == "__main__"
assert table.__name__ == "csv"
Output
__main__
json
csv
True

How it works:

  1. The file that you run is the main module, so its __name__ is "__main__".
  2. An imported module’s __name__ is its module name, "json".
  3. as table changes only the name in your namespace. The module still calls itself csv.
  4. A module is loaded once. Every later import returns the same object from sys.modules, so is gives True.

M08-W03 · Fix the bug: a module that cannot be found

Section titled “M08-W03 · Fix the bug: a module that cannot be found”
Warm-up

Fix the bug: this script must print whether the sales file exists and its name. It stops with ModuleNotFoundError: No module named 'Pathlib'.

Expected output
True sales.csv
Starter
from Pathlib import Path
sales = Path("data/sales.csv")
print(sales.exists(), sales.name)
# TODO: fix the import
Hint 1

Module names are case-sensitive, like variable names.

Hint 2

Standard library module names are lowercase: pathlib, csv, json.

Solution
from pathlib import Path
sales = Path("data/sales.csv")
print(sales.exists(), sales.name)
assert sales.exists()
Output
True sales.csv

How it works:

  1. Python searched every folder of sys.path for Pathlib and found nothing, because the module is called pathlib.
  2. The class inside it is Path with a capital P. Classes use CapWords names, modules use lowercase names (PEP 8).
  3. exists() is True when you run the script from the course folder, which holds data/.

Alternative: if the name is right and the error stays, the package is missing from the active environment. Check it with python -c "import sys; print(sys.prefix)" and install it into that environment.

Warm-up

units.py converts sensor readings and has a self-test at the top level, so every import prints the self-test. Move the self-test into a function main() and call it under a main guard. Then write check_import.py, which imports units, asserts that 0 °C is 32 °F and prints one line. Run python units.py, then python check_import.py.

Expected output
Self-test: 21.5 °C is 70.7 °F
Imported units without side effects
units.py (starter)
"""units.py: temperature conversions for sensor readings."""
def to_fahrenheit(celsius):
"""Return the temperature in °F."""
return celsius * 9 / 5 + 32
reading = 21.5
print(f"Self-test: {reading} °C is {to_fahrenheit(reading):.1f} °F")
# TODO: move the self-test into main() and add the main guard
# TODO: write check_import.py
Hint 1

The guard is if __name__ == "__main__": followed by an indented main().

Hint 2

check_import.py starts with import units. It must sit in the same folder as units.py, because that folder is sys.path[0].

Solution
units.py
"""units.py: temperature conversions for sensor readings."""
def to_fahrenheit(celsius):
"""Return the temperature in °F."""
return celsius * 9 / 5 + 32
def main():
"""Self-test with a reading from data/readings.txt."""
reading = 21.5
result = to_fahrenheit(reading)
assert round(result, 1) == 70.7
print(f"Self-test: {reading} °C is {result:.1f} °F")
if __name__ == "__main__":
main()
Output
Self-test: 21.5 °C is 70.7 °F
check_import.py
"""check_import.py: importing units must print nothing."""
import units
assert units.to_fahrenheit(0) == 32
print("Imported", units.__name__, "without side effects")
Output
Imported units without side effects

How it works:

  1. python units.py runs the file as __main__, so the guard is true and main() prints the self-test.
  2. import units runs the same file with __name__ == "units". The guard is false: the import defines to_fahrenheit and main and prints nothing.
  3. Only check_import.py’s own print() appears.

M08-W05 · A positional argument and an option

Section titled “M08-W05 · A positional argument and an option”
Warm-up

Write the code: build an argparse parser for a script top_lines.py with a positional argument path and an option --top that takes an int with the default 5. Parse the two argument lists in the starter and print path and top for each.

Expected output
data/sales.csv 5
data/sales.csv 3
Starter
import argparse
parser = argparse.ArgumentParser(prog="top_lines")
# TODO: add the positional argument path
# TODO: add the option --top (int, default 5)
for argv in [["data/sales.csv"], ["data/sales.csv", "--top", "3"]]:
args = parser.parse_args(argv)
# TODO: print args.path and args.top
Hint 1

A positional argument has a bare name: parser.add_argument("path"). An option starts with --.

Hint 2

parser.add_argument("--top", type=int, default=5).

Solution
import argparse
parser = argparse.ArgumentParser(prog="top_lines")
parser.add_argument("path", help="sales CSV file")
parser.add_argument("--top", type=int, default=5, help="lines to show")
for argv in [["data/sales.csv"], ["data/sales.csv", "--top", "3"]]:
args = parser.parse_args(argv)
print(args.path, args.top)
assert parser.parse_args(["x.csv"]).top == 5
assert parser.parse_args(["x.csv", "--top", "3"]).top == 3
Output
data/sales.csv 5
data/sales.csv 3

How it works:

  1. path has no dashes, so it is positional and required.
  2. --top is optional. Without it, argparse uses the default 5.
  3. type=int converts the text "3" to the int 3.

Alternative: add a short form with parser.add_argument("-n", "--top", ...). Then -n 3 and --top 3 both work, and the attribute is still args.top (the long name wins).

M08-W06 · Predict the output: types, choices and flags

Section titled “M08-W06 · Predict the output: types, choices and flags”
Warm-up

Predict the output of this parser test. Pay attention to the types, the dash in --min-revenue and the flag that is not given.

Acceptance criteria:

  • Write your prediction line by line, then run the code.
  • Your prediction matches the Output in the solution.
Starter
import argparse
parser = argparse.ArgumentParser(prog="filter_sales")
parser.add_argument("--min-revenue", type=float, default=0.0)
parser.add_argument("--channel", choices=["store", "online"], default="store")
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args(["--channel", "online", "--min-revenue", "100"])
print(args.min_revenue, args.channel, args.verbose)
print(type(args.min_revenue).__name__)
print(vars(args))
# TODO: write your prediction for each line before you run it
Hint 1

argparse turns a dash inside an option name into an underscore in the attribute name.

Hint 2

vars(obj) returns the attributes of an object as a dict. A store_true flag that is absent is False.

Solution
import argparse
parser = argparse.ArgumentParser(prog="filter_sales")
parser.add_argument("--min-revenue", type=float, default=0.0)
parser.add_argument("--channel", choices=["store", "online"], default="store")
parser.add_argument("--verbose", action="store_true")
args = parser.parse_args(["--channel", "online", "--min-revenue", "100"])
print(args.min_revenue, args.channel, args.verbose)
print(type(args.min_revenue).__name__)
print(vars(args))
assert args.min_revenue == 100.0
assert args.verbose is False
Output
100.0 online False
float
{'min_revenue': 100.0, 'channel': 'online', 'verbose': False}

How it works:

  1. type=float converts the text "100" to 100.0.
  2. "online" is one of the choices, so argparse accepts it.
  3. --verbose is missing, so the flag is False.
  4. vars() shows the Namespace as a dict, in the order of the add_argument() calls. The key is min_revenue, with an underscore.
Warm-up

Write the code: a script store_city.py takes a store id from the command line and prints the city of that store from data/stores.csv. With no argument, it uses S01. Use sys.argv, not argparse. Run it as python store_city.py S05.

Expected output
Arguments: ['S05']
Store S05 is in Atlanta
store_city.py (starter)
import csv
import sys
# TODO: take the store id from sys.argv, or "S01" when there is no argument
with open("data/stores.csv", newline="", encoding="utf-8") as file:
cities = {row["store_id"]: row["city"] for row in csv.DictReader(file)}
# TODO: print the arguments and the sentence
Hint 1

sys.argv[0] is the script name. The arguments start at index 1.

Hint 2

Check the length first: sys.argv[1] if len(sys.argv) > 1 else "S01".

Solution
store_city.py
"""store_city.py: print the city of the store named on the command line."""
import csv
import sys
store_id = sys.argv[1] if len(sys.argv) > 1 else "S01" # default when no argument
with open("data/stores.csv", newline="", encoding="utf-8") as file:
cities = {row["store_id"]: row["city"] for row in csv.DictReader(file)}
print("Arguments:", sys.argv[1:])
print(f"Store {store_id} is in {cities[store_id]}")
assert store_id in cities
Output
Arguments: ['S05']
Store S05 is in Atlanta

How it works:

  1. python store_city.py S05 puts ["store_city.py", "S05"] into sys.argv, so sys.argv[1:] is ["S05"].
  2. The conditional expression picks the argument when there is one and the default otherwise. Without the length check, sys.argv[1] raises IndexError when you run the script with no argument.
  3. The dict comprehension maps each store id to its city, so one lookup answers the question.

Alternative: argparse with parser.add_argument("store_id", nargs="?", default="S01", choices=sorted(cities)) gives the same default, rejects unknown ids with a clear message and adds --help. For more than one argument, argparse is the better choice.

Warm-up

Write the code: a function in_virtualenv() that returns True when the code runs inside a virtual environment. Print the environment folder name and the result.

Expected output
Environment: .venv
Inside a virtual environment: True
Starter
import sys
from pathlib import Path
def in_virtualenv():
"""Return True inside a virtual environment."""
# TODO: compare two attributes of sys
# TODO: print the environment folder name and in_virtualenv()
Hint 1

sys.prefix is the active environment. sys.base_prefix is the Python installation it came from.

Hint 2

Path(sys.prefix).name is the last part of the folder path, for example .venv.

Solution
import sys
from pathlib import Path
def in_virtualenv():
"""Return True inside a virtual environment."""
return sys.prefix != sys.base_prefix
print("Environment:", Path(sys.prefix).name)
print("Inside a virtual environment:", in_virtualenv())
assert in_virtualenv()
Output
Environment: .venv
Inside a virtual environment: True

How it works:

  1. Inside a virtual environment, sys.prefix points to the environment folder and sys.base_prefix to the base Python. Outside one, both are the same folder.
  2. The course environment is called .venv, so the name shows it.

Alternative: activation sets the environment variable VIRTUAL_ENV, and os.environ.get("VIRTUAL_ENV") reads it. But uv run and .venv/bin/python script.py can run without activation, so the sys.prefix test is more reliable.

M08-C01 · A module and a script that imports it

Section titled “M08-C01 · A module and a script that imports it”
Core

Write discounts.py with a function apply_discount(price, rate) that returns the discounted price rounded to cents and raises ValueError for a rate outside 0 to 1. Give it a main() that prints the price of the Noise-Cancelling Headphones (249.00 USD) at each discount rate of the sales file (0, 5%, 10%, 20%), under a main guard. Then write price_list.py, which imports discounts and prints the 20% Black Friday price of three products from data/products.csv. Running python price_list.py must print only this:

Expected output
P001 Wireless Earbuds 79.99 -> 63.99
P002 Noise-Cancelling Headphones 249.00 -> 199.20
P006 Espresso Machine 349.00 -> 279.20
discounts.py and price_list.py (starter)
# discounts.py
RATES = [0.0, 0.05, 0.1, 0.2]
def apply_discount(price, rate):
# TODO: check the rate, return the rounded price
...
# TODO: main() prints the headphones price at every rate; add the main guard
# price_list.py
# TODO: import discounts
PRODUCTS = {
"P001": ("Wireless Earbuds", 79.99),
"P002": ("Noise-Cancelling Headphones", 249.00),
"P006": ("Espresso Machine", 349.00),
}
# TODO: print id, name, price and the 20% price of each product
Hint 1

The check if not 0 <= rate < 1: raise ValueError(...) rejects bad rates.

Hint 2

f"{name:<28}" pads the name to 28 characters, and f"{price:7.2f}" right-aligns a price in 7 characters.

Solution
discounts.py
"""discounts.py: price helpers for promotions."""
RATES = [0.0, 0.05, 0.1, 0.2] # the discount levels used in data/sales.csv
def apply_discount(price, rate):
"""Return the price after a discount rate, rounded to cents."""
if not 0 <= rate < 1:
raise ValueError(f"rate must be in [0, 1), got {rate}")
return round(price * (1 - rate), 2)
def main():
"""Print the price of the Noise-Cancelling Headphones at every rate."""
for rate in RATES:
print(f"{rate:>4.0%} off: {apply_discount(249.00, rate):7.2f} USD")
if __name__ == "__main__":
main()
Output
0% off: 249.00 USD
5% off: 236.55 USD
10% off: 224.10 USD
20% off: 199.20 USD
price_list.py
"""price_list.py: a Black Friday price list built with discounts.py."""
import discounts
# Three products from data/products.csv: id -> (name, unit price in USD).
PRODUCTS = {
"P001": ("Wireless Earbuds", 79.99),
"P002": ("Noise-Cancelling Headphones", 249.00),
"P006": ("Espresso Machine", 349.00),
}
for product_id, (name, price) in PRODUCTS.items():
promo = discounts.apply_discount(price, 0.2)
print(f"{product_id} {name:<28} {price:7.2f} -> {promo:7.2f}")
assert discounts.apply_discount(100.0, 0.1) == 90.0
assert discounts.__name__ == "discounts"
Output
P001 Wireless Earbuds 79.99 -> 63.99
P002 Noise-Cancelling Headphones 249.00 -> 199.20
P006 Espresso Machine 349.00 -> 279.20

How it works:

  1. python discounts.py runs the module as __main__, so main() prints the four prices.
  2. import discounts in price_list.py loads the same file as the module discounts. The guard is false, so the table of prices does not appear.
  3. price_list.py uses only the function. The formula lives in one place; a fix there fixes every script.
  4. The :>4.0% spec shows a rate as a whole percentage, right-aligned in 4 characters.

Alternative: from discounts import apply_discount imports only the function. Both forms run discounts.py once; they differ only in the names they bind.

Core

Write the code: a function build_parser() for a command topsales with a positional path converted to Path, an option --by limited to category, region and channel (default category), an option --top (int, default 5), an option --year (int, no default) and a flag --share. Parse the three argument lists in the starter and print each Namespace as a dict.

Expected output
{'path': 'data/sales.csv', 'by': 'category', 'top': 5, 'year': None, 'share': False}
{'path': 'data/sales.csv', 'by': 'region', 'top': 2, 'year': None, 'share': False}
{'path': 'data/sales.csv', 'by': 'category', 'top': 5, 'year': 2024, 'share': True}
Starter
import argparse
from pathlib import Path
def build_parser():
parser = argparse.ArgumentParser(prog="topsales")
# TODO: path, --by, --top, --year, --share
return parser
tests = [
["data/sales.csv"],
["data/sales.csv", "--by", "region", "--top", "2"],
["--share", "--year", "2024", "data/sales.csv"],
]
# TODO: parse each list and print vars(args) with the path as text
Hint 1

type=Path converts the text to a Path. choices=[...] limits the values. action="store_true" makes a flag.

Hint 2

A Path prints as PosixPath(...) or WindowsPath(...) inside a dict. Replace it with str(args.path) before you print, so the output is the same on every system.

Solution
import argparse
from pathlib import Path
def build_parser():
"""Return the parser of the topsales command."""
parser = argparse.ArgumentParser(prog="topsales")
parser.add_argument("path", type=Path, help="sales CSV file")
parser.add_argument(
"--by", choices=["category", "region", "channel"], default="category"
)
parser.add_argument("--top", type=int, default=5)
parser.add_argument("--year", type=int)
parser.add_argument("--share", action="store_true")
return parser
tests = [
["data/sales.csv"],
["data/sales.csv", "--by", "region", "--top", "2"],
["--share", "--year", "2024", "data/sales.csv"],
]
parser = build_parser()
for argv in tests:
values = vars(parser.parse_args(argv))
values["path"] = str(values["path"])
print(values)
last = parser.parse_args(tests[-1])
assert isinstance(last.path, Path) and last.year == 2024 and last.share
Output
{'path': 'data/sales.csv', 'by': 'category', 'top': 5, 'year': None, 'share': False}
{'path': 'data/sales.csv', 'by': 'region', 'top': 2, 'year': None, 'share': False}
{'path': 'data/sales.csv', 'by': 'category', 'top': 5, 'year': 2024, 'share': True}

How it works:

  1. The first list gives only the path, so every option takes its default. --year has no default, so it is None.
  2. Options and the positional can come in any order: the third list puts the flag and --year first.
  3. type=Path and type=int convert the text before your code sees it.
  4. build_parser() in its own function lets a test build a fresh parser at any time.

M08-C03 · A custom type for a discount rate

Section titled “M08-C03 · A custom type for a discount rate”
Core

Write the code: a function discount_rate(text) that converts text to a float and raises argparse.ArgumentTypeError unless the value is between 0 and 0.5. The sales file never discounts more than 20%, and a rate of 0.5 is the business limit. Test it directly on four values, then use it as the type of a --discount option.

Expected output
0.1 -> 0.1
0 -> 0.0
0.75 -> error: rate must be in [0, 0.5], got 0.75
-0.2 -> error: rate must be in [0, 0.5], got -0.2
0.2
0.0
Starter
import argparse
def discount_rate(text):
# TODO: float(text), check 0 <= value <= 0.5, raise ArgumentTypeError otherwise
...
for text in ["0.1", "0", "0.75", "-0.2"]:
# TODO: print the value, or the error message
...
parser = argparse.ArgumentParser(prog="promo")
# TODO: --discount with type=discount_rate and default 0.0
Hint 1

Catch the error in the test loop with try/except argparse.ArgumentTypeError as error: and print error.

Hint 2

A type function receives one string and returns the converted value. argparse also turns a ValueError from float() into an error message, so you do not need to catch it.

Solution
import argparse
def discount_rate(text):
"""Convert text to a discount rate between 0 and 0.5."""
value = float(text)
if not 0 <= value <= 0.5:
raise argparse.ArgumentTypeError(f"rate must be in [0, 0.5], got {value}")
return value
for text in ["0.1", "0", "0.75", "-0.2"]:
try:
print(text, "->", discount_rate(text))
except argparse.ArgumentTypeError as error:
print(text, "-> error:", error)
parser = argparse.ArgumentParser(prog="promo")
parser.add_argument("--discount", type=discount_rate, default=0.0)
print(parser.parse_args(["--discount", "0.2"]).discount)
print(parser.parse_args([]).discount)
assert discount_rate("0.5") == 0.5
Output
0.1 -> 0.1
0 -> 0.0
0.75 -> error: rate must be in [0, 0.5], got 0.75
-0.2 -> error: rate must be in [0, 0.5], got -0.2
0.2
0.0

How it works:

  1. float(text) converts the string. Bad text such as "ten" raises ValueError, and argparse reports it as invalid discount_rate value: 'ten'.
  2. The range check raises ArgumentTypeError with a clear message. argparse prints it after error: argument --discount: and exits with code 2.
  3. Because discount_rate is a plain function, the loop tests it without any parser.

Alternative: check the range after parse_args() and call parser.error("..."). That works, but the type function keeps the check next to the conversion and reuses it for every option that takes a rate.

M08-C04 · Fix the bugs: big order lines by product

Section titled “M08-C04 · Fix the bugs: big order lines by product”
Core

Fix the bugs: a sales manager wants the products that earn the most from big order lines (1,000 USD or more) in 2023. The script reads data/sales.csv and takes its settings from the command line, but it crashes. Fix it one error at a time until it prints the report below. Keep the argument list in the starter.

Expected output
55-inch 4K Smart TV 327,283.05
14-inch Ultrabook Laptop 307,472.40
Espresso Machine 11,656.60
Starter
import argparse
import csv
parser = argparse.ArgumentParser(prog="big_lines")
parser.add_argument("path")
parser.add_argument("--year", type=int, default=2024)
parser.add_argument("--top", default=3)
parser.add_argument("--min-revenue", default="0")
args = parser.parse_args(["data/sales.csv", "--year", "2023", "--min-revenue", "1000"])
totals = {}
with open(args.path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
revenue = float(row["revenue"])
if row["order_date"].startswith(args.year) and revenue >= args.min_revenue:
totals[row["product"]] = totals.get(row["product"], 0.0) + revenue
ranked = sorted(totals.items(), key=lambda item: item[1], reverse=True)[: args.top]
for product, revenue in ranked:
print(f"{product:<26} {revenue:>12,.2f}")
# TODO: run it, read the last traceback line, fix that bug, repeat
Hint 1

The first error is TypeError: startswith first arg must be str or a tuple of str, not int. --year is an int, but order_date is text.

Hint 2

Two options have no type. Every value without a type stays a string, and so does a string default.

Hint 3

The last error comes from the slice [: args.top]. Which keyword of add_argument() converts "3", and what should the defaults look like then?

Solution
import argparse
import csv
parser = argparse.ArgumentParser(prog="big_lines")
parser.add_argument("path")
parser.add_argument("--year", type=int, default=2024)
parser.add_argument("--top", type=int, default=3)
parser.add_argument("--min-revenue", type=float, default=0.0)
args = parser.parse_args(["data/sales.csv", "--year", "2023", "--min-revenue", "1000"])
totals = {}
with open(args.path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
revenue = float(row["revenue"])
if row["order_date"].startswith(str(args.year)) and revenue >= args.min_revenue:
totals[row["product"]] = totals.get(row["product"], 0.0) + revenue
ranked = sorted(totals.items(), key=lambda item: item[1], reverse=True)[: args.top]
for product, revenue in ranked:
print(f"{product:<26} {revenue:>12,.2f}")
assert isinstance(args.top, int) and isinstance(args.min_revenue, float)
assert ranked[0][0] == "55-inch 4K Smart TV"
Output
55-inch 4K Smart TV 327,283.05
14-inch Ultrabook Laptop 307,472.40
Espresso Machine 11,656.60

How it works:

  1. Bug 1, the year. type=int was right for --year: a year is a number, and argparse rejects --year 20x3. But str.startswith() needs text, so the comparison converts back with str(args.year).
  2. Bug 2, the minimum revenue. Without type, args.min_revenue is the string "1000", and revenue >= "1000" raises TypeError: '>=' not supported between instances of 'float' and 'str'. type=float with the float default 0.0 fixes it.
  3. Bug 3, the top count. Without type, a value typed on the command line is a string, and a slice needs an int. type=int fixes it. (argparse converts a string default with type too, but an int default says what you mean.)
  4. Each bug shows only after the previous one is fixed, because Python stops at the first error. Read the last traceback line every time.
  5. The result: two large electronics products earn almost all big-line revenue. The third product is far behind.
Core

Write the code: use the salesreport package of the lesson from Python. For 2024 only, print the number of order lines, the total revenue and the three largest categories with their share of the year’s revenue.

Expected output
2024: 11,147 lines, 1,950,934.24 USD
Electronics 939,924.77 48.2%
Home 397,844.84 20.4%
Sports 299,576.31 15.4%
Starter
from salesreport import load_sales, revenue_by, top_n, total_revenue
# TODO: load the 2024 lines
# TODO: print the count and the total
# TODO: print the top 3 categories with their share
Hint 1

load_sales("data/sales.csv", year=2024) filters while it reads.

Hint 2

top_n(revenue_by(rows, "category"), 3) returns a dict. Loop over .items() and divide each revenue by the total.

Solution
from salesreport import load_sales, revenue_by, top_n, total_revenue
rows = load_sales("data/sales.csv", year=2024)
total = total_revenue(rows)
print(f"2024: {len(rows):,} lines, {total:,.2f} USD")
for category, revenue in top_n(revenue_by(rows, "category"), 3).items():
print(f"{category:<12} {revenue:>12,.2f} {revenue / total:6.1%}")
assert len(rows) == 11_147
assert all(row["order_date"].startswith("2024") for row in rows)
Output
2024: 11,147 lines, 1,950,934.24 USD
Electronics 939,924.77 48.2%
Home 397,844.84 20.4%
Sports 299,576.31 15.4%

How it works:

  1. The salesreport/ folder sits in the current folder, which is on sys.path, so the import works without an install.
  2. __init__.py offers the four functions at the top level, so one from salesreport import ... line is enough.
  3. The functions return plain data, so the script formats the result its own way.

Alternative: from salesreport.stats import revenue_by imports from the submodule directly. Use the top-level names when the package offers them; they stay valid if the package moves code between files.

M08-C06 · Add an option to an existing CLI

Section titled “M08-C06 · Add an option to an existing CLI”
Core

Write the code: reuse build_parser() and format_report() from salesreport.cli. Add an option --channel with the choices store and online (default: both). Write run(argv) that loads the rows, keeps only the chosen channel and prints the report. Run it for the top 3 categories of the online channel.

Expected output
Sales report: 8,495 order lines, revenue 1,519,466.47 USD
Top 3 by category:
1. Electronics 767,072.48
2. Home 284,066.00
3. Sports 226,771.66
Starter
from salesreport import load_sales
from salesreport.cli import build_parser, format_report
def run(argv):
parser = build_parser()
# TODO: add --channel with choices store and online
args = parser.parse_args(argv)
# TODO: load the rows, filter by channel if given, print the report lines
run(["data/sales.csv", "--channel", "online", "--top", "3"])
Hint 1

build_parser() returns an ordinary parser. You can call add_argument() on it again.

Hint 2

Without a default, args.channel is None. Filter only when it is not None: [row for row in rows if row["channel"] == args.channel].

Solution
from salesreport import load_sales
from salesreport.cli import build_parser, format_report
def run(argv):
"""Run the sales report with an extra --channel filter."""
parser = build_parser()
parser.add_argument("--channel", choices=["store", "online"])
args = parser.parse_args(argv)
rows = load_sales(args.path, year=args.year)
if args.channel is not None:
rows = [row for row in rows if row["channel"] == args.channel]
lines = format_report(rows, args.by, args.top, args.share)
for line in lines:
print(line)
return lines
lines = run(["data/sales.csv", "--channel", "online", "--top", "3"])
assert lines[0].startswith("Sales report: 8,495 order lines")
Output
Sales report: 8,495 order lines, revenue 1,519,466.47 USD
Top 3 by category:
1. Electronics 767,072.48
2. Home 284,066.00
3. Sports 226,771.66

How it works:

  1. The package already has a tested parser, so run() adds one option instead of copying the others.
  2. format_report() takes any list of rows, so it works on the filtered list unchanged.
  3. Returning the lines lets the assert check the first line. The 8,495 online lines match the dataset.

Alternative: add --channel inside salesreport/cli.py itself and filter in main(). That is the right home once the option is part of the product; the wrapper above is a quick way to try it first.

Core

Write the code: parse the pyproject.toml text of a churn model project with tomllib.loads(). Print the name and version, the required Python, one line per dependency with its name and its specifier, and the entry-point commands.

Expected output
churn-model 1.2.0 needs Python >=3.12
pandas >=3.1,<4
scikit-learn ~=1.9
joblib >=1.4
command churn-train -> churn_model.train:main
command churn-predict -> churn_model.predict:main
Starter
import tomllib
PYPROJECT = """
[project]
name = "churn-model"
version = "1.2.0"
requires-python = ">=3.12"
dependencies = ["pandas>=3.1,<4", "scikit-learn~=1.9", "joblib>=1.4"]
[project.scripts]
churn-train = "churn_model.train:main"
churn-predict = "churn_model.predict:main"
"""
# TODO: parse the text, print the fields
Hint 1

tomllib.loads(text) parses a string; tomllib.load(file) parses an open binary file.

Hint 2

A requirement string starts with the name. Split at the first character of the specifier: the first >, <, =, ~ or !. A loop that stops at the first such character works.

Solution
import tomllib
PYPROJECT = """
[project]
name = "churn-model"
version = "1.2.0"
requires-python = ">=3.12"
dependencies = ["pandas>=3.1,<4", "scikit-learn~=1.9", "joblib>=1.4"]
[project.scripts]
churn-train = "churn_model.train:main"
churn-predict = "churn_model.predict:main"
"""
def split_requirement(requirement):
"""Split 'pandas>=3.1,<4' into ('pandas', '>=3.1,<4')."""
for index, char in enumerate(requirement):
if char in "<>=~!":
return requirement[:index], requirement[index:]
return requirement, ""
config = tomllib.loads(PYPROJECT)
project = config["project"]
print(project["name"], project["version"], "needs Python", project["requires-python"])
for requirement in project["dependencies"]:
name, spec = split_requirement(requirement)
print(f" {name:<14} {spec}")
for command, target in project["scripts"].items():
print(f"command {command} -> {target}")
assert split_requirement("joblib>=1.4") == ("joblib", ">=1.4")
assert len(project["scripts"]) == 2
Output
churn-model 1.2.0 needs Python >=3.12
pandas >=3.1,<4
scikit-learn ~=1.9
joblib >=1.4
command churn-train -> churn_model.train:main
command churn-predict -> churn_model.predict:main

How it works:

  1. tomllib.loads() returns nested dicts: config["project"]["scripts"] is the [project.scripts] table.
  2. split_requirement() finds the first operator character and splits there.
  3. Each entry point maps a command to module:function. The installer creates both commands in the environment.

Alternative: the packaging library, which pip and most tools use, parses requirements fully, markers and extras included: Requirement("pandas>=3.1,<4").name. It comes with the course environment as a dependency of other packages.

Core

Write the code: a requirements file mixes pins, ranges, bare names, comments and blank lines. Count the requirement lines, list the ones that are not pinned with == and print whether the file is fully pinned.

Expected output
Requirements: 7
Not pinned: ['matplotlib>=3.11', 'scikit-learn~=1.9', 'pyyaml', 'joblib==1.6.*']
Fully pinned: False
Starter
REQUIREMENTS = """\
# Analysis of data/sales.csv
pandas==3.1.1
numpy==2.5.4
matplotlib>=3.11
scikit-learn~=1.9
pyyaml
joblib==1.6.*
tzdata==2026.6 ; sys_platform == "win32"
"""
# TODO: skip blank lines and comments
# TODO: count requirements, list the unpinned ones, print the verdict
Hint 1

line.strip() removes spaces; skip the line when it is empty or starts with #.

Hint 2

Cut off an environment marker first: line.split(";")[0].strip(). A line is pinned when the rest contains == and no *.

Solution
REQUIREMENTS = """\
# Analysis of data/sales.csv
pandas==3.1.1
numpy==2.5.4
matplotlib>=3.11
scikit-learn~=1.9
pyyaml
joblib==1.6.*
tzdata==2026.6 ; sys_platform == "win32"
"""
requirements = []
for line in REQUIREMENTS.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
requirements.append(line.split(";")[0].strip())
unpinned = [req for req in requirements if "==" not in req or "*" in req]
print("Requirements:", len(requirements))
print("Not pinned:", unpinned)
print("Fully pinned:", not unpinned)
assert len(requirements) == 7
assert unpinned == ["matplotlib>=3.11", "scikit-learn~=1.9", "pyyaml", "joblib==1.6.*"]
Output
Requirements: 7
Not pinned: ['matplotlib>=3.11', 'scikit-learn~=1.9', 'pyyaml', 'joblib==1.6.*']
Fully pinned: False

How it works:

  1. Comments and blank lines are not requirements, so the loop skips them.
  2. The marker after ; is a condition, not part of the version. split(";")[0] drops it before the test.
  3. matplotlib>=3.11 and scikit-learn~=1.9 are ranges; pyyaml accepts any version.
  4. joblib==1.6.* contains == but is a range too: the wildcard accepts 1.6.0, 1.6.1 and every later 1.6 release. So the test also rejects any line with *.
  5. The file is not reproducible until all four are pinned, for example with uv pip compile.
Core

Write the code: a function shadowing_names(filenames, installed) that returns the sorted module names of the .py files that hide a standard library module or one of the installed packages. Test it on the file list of a messy project folder.

Expected output
Rename these files: ['email', 'pandas', 'random', 'statistics']
Starter
import sys
from pathlib import Path
project_files = [
"clean_sales.py", "statistics.py", "pandas.py", "report.py",
"random.py", "notes.txt", "email.py", "train_model.py",
]
installed = {"pandas", "numpy", "sklearn", "matplotlib"}
def shadowing_names(filenames, installed):
# TODO: keep .py files whose stem is in sys.stdlib_module_names or installed
...
# TODO: print the result
Hint 1

Path(name).suffix == ".py" keeps Python files. Path(name).stem is the module name.

Hint 2

sys.stdlib_module_names is a frozenset. The union sys.stdlib_module_names | installed holds every name to avoid.

Solution
import sys
from pathlib import Path
project_files = [
"clean_sales.py", "statistics.py", "pandas.py", "report.py",
"random.py", "notes.txt", "email.py", "train_model.py",
]
installed = {"pandas", "numpy", "sklearn", "matplotlib"}
def shadowing_names(filenames, installed):
"""Return the module names of .py files that hide another module."""
taken = sys.stdlib_module_names | installed
paths = [Path(name) for name in filenames]
return sorted(p.stem for p in paths if p.suffix == ".py" and p.stem in taken)
bad = shadowing_names(project_files, installed)
print("Rename these files:", bad)
assert bad == ["email", "pandas", "random", "statistics"]
assert shadowing_names(["report.py"], installed) == []
Output
Rename these files: ['email', 'pandas', 'random', 'statistics']

How it works:

  1. The script folder comes first in sys.path, so each of these files wins over the real module.
  2. email.py is a surprise for many people: email is a standard library package, and other standard modules import it: http.client does, so urllib.request breaks too.
  3. notes.txt is not a module, so the suffix test skips it.

Alternative: on a real folder, pass [p.name for p in Path(".").glob("*.py")] as the file list, and build installed from importlib.metadata.packages_distributions(), which maps every importable top-level name to its distribution.

M08-C10 · Interpret: run by path or by module name

Section titled “M08-C10 · Interpret: run by path or by module name”
Core

Interpret a result: run salesreport/cli.py by its path and the package with python -m salesreport, both from Python with subprocess.run(). Print the exit code and the last line of output of each. Then explain the difference in two sentences.

Expected output
by path: exit 1: ImportError: attempted relative import with no known parent package
with -m: exit 0: 1. Electronics 1,808,108.17
Starter
import subprocess
import sys
commands = {
"by path": [sys.executable, "salesreport/cli.py", "data/sales.csv", "--top", "1"],
"with -m": [sys.executable, "-m", "salesreport", "data/sales.csv", "--top", "1"],
}
for label, command in commands.items():
# TODO: run the command, capture the text output
# TODO: print the label, the exit code and the last line of stdout or stderr
...
Hint 1

subprocess.run(command, capture_output=True, text=True) returns an object with .returncode, .stdout and .stderr. Module 09 covers subprocess in depth.

Hint 2

(result.stdout or result.stderr).splitlines()[-1] gives the last line of whichever stream has text.

Solution
import subprocess
import sys
commands = {
"by path": [sys.executable, "salesreport/cli.py", "data/sales.csv", "--top", "1"],
"with -m": [sys.executable, "-m", "salesreport", "data/sales.csv", "--top", "1"],
}
codes = {}
for label, command in commands.items():
result = subprocess.run(command, capture_output=True, text=True)
last_line = (result.stdout or result.stderr).splitlines()[-1]
codes[label] = result.returncode
print(f"{label}: exit {result.returncode}: {last_line}")
assert codes == {"by path": 1, "with -m": 0}
Output
by path: exit 1: ImportError: attempted relative import with no known parent package
with -m: exit 0: 1. Electronics 1,808,108.17

How it works:

  1. sys.executable is the path of the Python that runs this script, so both commands use the same environment.
  2. By path, cli.py runs as a lone script with no parent package. Its first relative import, from . import __version__, fails, and an uncaught exception gives exit code 1.
  3. With -m, Python imports the package salesreport first and runs __main__.py, so every relative import has a parent. The report runs and main() returns 0.

Interpretation: a file inside a package is not a standalone script. Run a package by its module name with python -m, from the folder that contains it.

M08-C11 · Choose and justify: version specifiers

Section titled “M08-C11 · Choose and justify: version specifiers”
Core

Choose a method and justify it: pick one version specifier for each situation below. Check your choice against a list of real and future version numbers with the packaging library, which comes with the course environment.

  1. A library you publish needs pandas 3.1 or newer, and you have not tested pandas 4.
  2. A team analysis must use exactly the pandas the results were produced with.
  3. You accept bug-fix releases of scikit-learn 1.9 only.
Expected output
library pandas>=3.1,<4 accepts ['3.1.0', '3.1.1', '3.2.0']
analysis pandas==3.1.1 accepts ['3.1.1']
scikit-learn~=1.9.0 accepts 1.9.0: True
scikit-learn~=1.9.0 accepts 1.9.1: True
scikit-learn~=1.9.0 accepts 1.10.0: False
Starter
from packaging.specifiers import SpecifierSet
candidates = ["3.0.2", "3.1.0", "3.1.1", "3.2.0", "4.0.0"]
choices = {
"library": "", # TODO
"analysis": "", # TODO
}
# TODO: for each choice, print the candidates it accepts
# TODO: scikit-learn: test "1.9.0", "1.9.1", "1.10.0"
Hint 1

SpecifierSet(">=3.1").contains("3.2.0") returns True. Several conditions go in one string, separated by commas.

Hint 2

A range with an upper bound stops before the next major release. ~=1.9.0 means >=1.9.0, ==1.9.*.

Solution
from packaging.specifiers import SpecifierSet
candidates = ["3.0.2", "3.1.0", "3.1.1", "3.2.0", "4.0.0"]
choices = {
"library": ">=3.1,<4",
"analysis": "==3.1.1",
}
for situation, spec in choices.items():
accepted = [v for v in candidates if SpecifierSet(spec).contains(v)]
print(f"{situation:<9} pandas{spec:<9} accepts {accepted}")
sklearn_spec = SpecifierSet("~=1.9.0")
for v in ["1.9.0", "1.9.1", "1.10.0"]:
print(f"scikit-learn~=1.9.0 accepts {v}: {sklearn_spec.contains(v)}")
assert not SpecifierSet(choices["library"]).contains("4.0.0")
assert [v for v in candidates if SpecifierSet("==3.1.1").contains(v)] == ["3.1.1"]
Output
library pandas>=3.1,<4 accepts ['3.1.0', '3.1.1', '3.2.0']
analysis pandas==3.1.1 accepts ['3.1.1']
scikit-learn~=1.9.0 accepts 1.9.0: True
scikit-learn~=1.9.0 accepts 1.9.1: True
scikit-learn~=1.9.0 accepts 1.10.0: False

How it works and why:

  1. Library: >=3.1,<4. It allows every 3.x release from 3.1, so users can combine your library with other packages. The upper bound stops at the next major version, which may break your code.
  2. Analysis: ==3.1.1. A pin is the only specifier that gives the same version every time. Put it in a lock file or a pinned requirements file, not in a library’s dependencies.
  3. Bug fixes only: ~=1.9.0. It allows 1.9.1 and rejects 1.10.0. Note that ~=1.9 would allow 1.10: the last number written is the one that may grow.

M08-C12 · Refactor: hard-coded settings to a CLI

Section titled “M08-C12 · Refactor: hard-coded settings to a CLI”
Core

Refactor: the script in the starter hard-codes the file, the year and the number of rows. Turn it into a reusable module: a build_parser() function, a top_stores(path, year, top) function that returns data, and a main(argv=None) that prints. Test main() with an argument list for the top 2 stores of 2023.

Expected output
S07 204,366.16
S10 188,144.28
Starter
import csv
PATH = "data/sales.csv"
YEAR = "2023"
TOP = 2
totals = {}
with open(PATH, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
if row["order_date"].startswith(YEAR):
totals[row["store_id"]] = totals.get(row["store_id"], 0) + float(row["revenue"])
for store, revenue in sorted(totals.items(), key=lambda x: x[1], reverse=True)[:TOP]:
print(store, round(revenue, 2))
# TODO: build_parser(), top_stores(path, year, top), main(argv=None) + main guard
Hint 1

Turn each constant into an argument: path positional, --year (int, default 2023), --top (int, default 3).

Hint 2

top_stores() returns a list of (store_id, revenue) pairs and prints nothing. main() parses, calls it, prints and returns 0.

Solution
import argparse
import csv
def build_parser():
"""Return the parser of the top_stores command."""
parser = argparse.ArgumentParser(prog="top_stores")
parser.add_argument("path", help="sales CSV file")
parser.add_argument("--year", type=int, default=2023)
parser.add_argument("--top", type=int, default=3)
return parser
def top_stores(path, year, top):
"""Return the top (store_id, revenue) pairs of one year."""
totals = {}
with open(path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
if row["order_date"].startswith(str(year)):
store = row["store_id"]
totals[store] = totals.get(store, 0.0) + float(row["revenue"])
ranked = sorted(totals.items(), key=lambda item: item[1], reverse=True)
return [(store, round(revenue, 2)) for store, revenue in ranked[:top]]
def main(argv=None):
"""Print the top stores. argv=None reads the real command line."""
args = build_parser().parse_args(argv)
for store, revenue in top_stores(args.path, args.year, args.top):
print(f"{store} {revenue:>12,.2f}")
return 0
exit_code = main(["data/sales.csv", "--year", "2023", "--top", "2"])
assert exit_code == 0
assert len(top_stores("data/sales.csv", 2024, 4)) == 4
Output
S07 204,366.16
S10 188,144.28

How it works:

  1. Each hard-coded constant became an argument with a default, so the old behavior is one command away.
  2. top_stores() returns data. A test, a notebook or another module can now use it.
  3. main(argv=None) reads the real command line when you run the file, and a list when a test calls it.
  4. Here the code calls main([...]) with a list, as a test would. In a file of its own, replace the last three lines with the main guard, if __name__ == "__main__": and main(), and run python top_stores.py data/sales.csv --year 2023 --top 2.
Core

Write the code: an analysis imports pandas, sklearn, matplotlib and yaml. Map each import name to its distribution name with importlib.metadata.packages_distributions() and print a sorted, pinned requirements list.

Expected output
matplotlib==3.11.2
pandas==3.1.1
PyYAML==6.0.3
scikit-learn==1.9.1
Starter
from importlib.metadata import packages_distributions, version
imports = ["pandas", "sklearn", "matplotlib", "yaml"]
# TODO: map each import name to its distribution
# TODO: print "distribution==version" lines, sorted case-insensitively
Hint 1

packages_distributions() returns a dict such as {"sklearn": ["scikit-learn"], ...}. The value is a list, because one import name can come from several distributions.

Hint 2

Sort with key=str.lower, so PyYAML sits between pandas and scikit-learn.

Solution
from importlib.metadata import packages_distributions, version
imports = ["pandas", "sklearn", "matplotlib", "yaml"]
mapping = packages_distributions()
distributions = sorted({mapping[name][0] for name in imports}, key=str.lower)
pins = [f"{dist}=={version(dist)}" for dist in distributions]
print("\n".join(pins))
assert "scikit-learn" in distributions
assert all("==" in pin for pin in pins)
Output
matplotlib==3.11.2
pandas==3.1.1
PyYAML==6.0.3
scikit-learn==1.9.1

How it works:

  1. The import name and the distribution name differ for two of the four: sklearn comes from scikit-learn and yaml from PyYAML.
  2. version() takes the distribution name and reads the installed version.
  3. The list pins the direct dependencies only. A lock file adds their dependencies too.

Alternative: uv pip freeze or python -m pip freeze prints every installed package with its version, transitive ones included. That is complete, but it also lists tools that the analysis never uses.

Core

Fix the bug: the package salesmini has two modules. loader.py reads the revenue column and takes the column name from stats.py. stats.py computes the mean and imports the loader. The script report.py must print the mean line revenue of data/sales.csv, but the import fails:

Terminal
cd exercises/c14_broken && python report.py 2>&1 | tail -n 1 | cut -d "(" -f 1-2 | fold -s -w 90
Output
ImportError: cannot import name 'REVENUE_COLUMN' from partially initialized module
'salesmini.stats' (most likely due to a circular import)

This page keeps the broken copy in exercises/c14_broken/. cut drops the file path that Python adds at the end in parentheses, and fold wraps the long line. Untangle the modules so that no two of them import each other. Keep report.py short.

Expected output
Mean line revenue: 177.80 USD
salesmini/loader.py (starter)
"""loader.py (broken): reads the file, but imports a constant from stats."""
import csv
from .stats import REVENUE_COLUMN
def load_revenues(path):
"""Return the revenue column of a sales CSV file as floats."""
with open(path, newline="", encoding="utf-8") as file:
return [float(row[REVENUE_COLUMN]) for row in csv.DictReader(file)]
salesmini/stats.py (starter)
"""stats.py (broken): imports the loader, then defines the constant."""
from .loader import load_revenues
REVENUE_COLUMN = "revenue"
def mean_revenue(path):
"""Return the mean line revenue of a sales CSV file."""
revenues = load_revenues(path)
return sum(revenues) / len(revenues)
report.py (starter)
from salesmini.stats import mean_revenue
print(f"Mean line revenue: {mean_revenue('data/sales.csv'):.2f} USD")
# TODO: break the import cycle between loader.py and stats.py
Hint 1

Follow the imports in the traceback: report imports stats, stats imports loader, and loader imports stats again, which has not finished running yet.

Hint 2

The cycle exists only because of one shared constant. Where can a constant live so that both modules can import it, while it imports nothing itself?

Solution

Move the shared constants into a third module, settings.py. The imports now flow one way: settings ← loader ← stats ← report.

salesmini/settings.py
"""settings.py: shared constants; imports nothing from the package."""
REVENUE_COLUMN = "revenue"
SALES_PATH = "data/sales.csv"
salesmini/loader.py
"""loader.py: read the revenue column; depends only on settings."""
import csv
from .settings import REVENUE_COLUMN
def load_revenues(path):
"""Return the revenue column of a sales CSV file as floats."""
with open(path, newline="", encoding="utf-8") as file:
return [float(row[REVENUE_COLUMN]) for row in csv.DictReader(file)]
salesmini/stats.py
"""stats.py: statistics; depends on loader, never the other way round."""
from .loader import load_revenues
def mean_revenue(path):
"""Return the mean line revenue of a sales CSV file."""
revenues = load_revenues(path)
return sum(revenues) / len(revenues)
report.py
"""report.py: print the mean line revenue."""
from salesmini.settings import SALES_PATH
from salesmini.stats import mean_revenue
mean = mean_revenue(SALES_PATH)
print(f"Mean line revenue: {mean:.2f} USD")
assert round(mean, 2) == 177.80
Output
Mean line revenue: 177.80 USD

How it works:

  1. report imports salesmini.stats. Python starts to run stats.py and puts the half-finished module into sys.modules.
  2. The first line of stats.py imports loader, whose first line asks stats for REVENUE_COLUMN. stats stopped at its first line, so the name does not exist yet: “partially initialized module”.
  3. settings.py imports nothing from the package, so it is always complete when another module needs it. loader depends on settings, stats depends on loader, and nothing points back.
  4. The mean of 177.80 USD matches the dataset’s mean line revenue.

Alternative: pass the column name as a parameter, load_revenues(path, column="revenue"), and drop the import from loader.py. Another quick fix is to move the import inside the function that uses it, but that hides the design problem. A one-way import graph is easier to read and to test.

Challenge

Write the code: tools such as git and uv have subcommands (uv add, uv sync), each with its own arguments. Build a salescli parser with two subcommands. summary PATH prints the line count and the total revenue. top PATH --by COLUMN --top N prints the ranking. Dispatch with set_defaults(func=...) and test both from a list.

Expected output
20,228 lines, 3,596,523.83 USD
East 993,683.72
South 891,766.07
Starter
import argparse
from salesreport import load_sales, revenue_by, top_n, total_revenue
def cmd_summary(args):
... # TODO
def cmd_top(args):
... # TODO
def build_parser():
parser = argparse.ArgumentParser(prog="salescli")
subparsers = parser.add_subparsers(dest="command", required=True)
# TODO: summary with path; top with path, --by, --top
return parser
def main(argv=None):
... # TODO: parse, then call args.func(args)
main(["summary", "data/sales.csv"])
main(["top", "data/sales.csv", "--by", "region", "--top", "2"])
Hint 1

summary = subparsers.add_parser("summary", help="...") returns a parser. Add arguments to it as usual.

Hint 2

summary.set_defaults(func=cmd_summary) stores the function in args.func when that subcommand is chosen. main() then calls args.func(args).

Hint 3

required=True in add_subparsers() makes argparse report an error when the user types no subcommand.

Solution
import argparse
from salesreport import load_sales, revenue_by, top_n, total_revenue
def cmd_summary(args):
"""Print the line count and the total revenue."""
rows = load_sales(args.path)
print(f"{len(rows):,} lines, {total_revenue(rows):,.2f} USD")
def cmd_top(args):
"""Print the largest groups."""
rows = load_sales(args.path)
for group, revenue in top_n(revenue_by(rows, args.by), args.top).items():
print(f"{group:<10} {revenue:>14,.2f}")
def build_parser():
"""Return the salescli parser with its two subcommands."""
parser = argparse.ArgumentParser(prog="salescli")
subparsers = parser.add_subparsers(dest="command", required=True)
summary = subparsers.add_parser("summary", help="count lines and revenue")
summary.add_argument("path")
summary.set_defaults(func=cmd_summary)
top = subparsers.add_parser("top", help="rank groups by revenue")
top.add_argument("path")
columns = ["category", "region", "channel"]
top.add_argument("--by", choices=columns, default="category")
top.add_argument("--top", type=int, default=5)
top.set_defaults(func=cmd_top)
return parser
def main(argv=None):
"""Parse the arguments and run the chosen subcommand."""
args = build_parser().parse_args(argv)
args.func(args)
return args.command
assert main(["summary", "data/sales.csv"]) == "summary"
assert main(["top", "data/sales.csv", "--by", "region", "--top", "2"]) == "top"
Output
20,228 lines, 3,596,523.83 USD
East 993,683.72
South 891,766.07

How it works:

  1. add_subparsers() adds a special positional argument: the subcommand name. dest="command" stores it in args.command.
  2. Each subcommand is a parser of its own, so top has --by and --top and summary does not.
  3. set_defaults(func=...) puts a function into the Namespace. main() does not need an if/elif chain to dispatch.
  4. python salescli.py --help lists the subcommands; python salescli.py top --help shows the options of top.

Alternative: one parser with a positional command argument and choices=["summary", "top"] is shorter, but every option then applies to every command. Subparsers scale better as the tool grows.

M08-X02 · Settings from defaults, a config file and the command line

Section titled “M08-X02 · Settings from defaults, a config file and the command line”
Challenge

Write the code: real tools take settings from three layers. The command line beats the config file, and the config file beats the built-in defaults. data/config.json holds thresholds.max_quantity and thresholds.max_discount. Build a parser whose defaults come from that file, and count the order lines of data/sales.csv that break the thresholds, first with the config values, then with --max-discount 0.1 on the command line.

Expected output
Built-in: {'max_quantity': 10, 'max_discount': 0.5}
From config.json: {'max_quantity': 50, 'max_discount': 0.2}
[]: max_quantity=50, max_discount=0.2 -> 0 lines break a limit
['--max-discount', '0.1']: max_quantity=50, max_discount=0.1 -> 1,439 lines break a limit
Starter
import argparse
import csv
import json
BUILT_IN = {"max_quantity": 10, "max_discount": 0.5}
def load_config(path):
# TODO: read the JSON file and return its "thresholds" values for our two keys
...
def build_parser(defaults):
# TODO: --max-quantity (int) and --max-discount (float); apply the defaults
...
def count_violations(path, max_quantity, max_discount):
# TODO: count lines with quantity > max_quantity or discount > max_discount
...
# TODO: merge BUILT_IN with the config file, parse [] and ["--max-discount", "0.1"]
Hint 1

Merge two dicts with {**BUILT_IN, **from_file}: keys of the second dict win.

Hint 2

parser.set_defaults(**defaults) sets the default of every argument whose dest matches a key. Note the underscore: the option --max-quantity has the dest max_quantity.

Hint 3

Convert row["quantity"] with int() and row["discount"] with float() before you compare.

Solution
import argparse
import csv
import json
BUILT_IN = {"max_quantity": 10, "max_discount": 0.5}
def load_config(path):
"""Return the threshold settings of a JSON config file."""
with open(path, encoding="utf-8") as file:
thresholds = json.load(file)["thresholds"]
return {key: thresholds[key] for key in BUILT_IN if key in thresholds}
def build_parser(defaults):
"""Return a parser whose defaults come from a dict."""
parser = argparse.ArgumentParser(prog="check_sales")
parser.add_argument("--max-quantity", type=int)
parser.add_argument("--max-discount", type=float)
parser.set_defaults(**defaults)
return parser
def count_violations(path, max_quantity, max_discount):
"""Count order lines above the quantity or the discount limit."""
count = 0
with open(path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
too_many = int(row["quantity"]) > max_quantity
discount_too_high = float(row["discount"]) > max_discount
count += too_many or discount_too_high
return count
from_file = load_config("data/config.json")
settings = {**BUILT_IN, **from_file}
print("Built-in:", BUILT_IN)
print("From config.json:", from_file)
parser = build_parser(settings)
results = []
for argv in [[], ["--max-discount", "0.1"]]:
args = parser.parse_args(argv)
n = count_violations("data/sales.csv", args.max_quantity, args.max_discount)
results.append(n)
print(f"{argv}: max_quantity={args.max_quantity}, "
f"max_discount={args.max_discount} -> {n:,} lines break a limit")
assert settings["max_quantity"] == 50
assert results[0] == 0 and results[1] > 0
Output
Built-in: {'max_quantity': 10, 'max_discount': 0.5}
From config.json: {'max_quantity': 50, 'max_discount': 0.2}
[]: max_quantity=50, max_discount=0.2 -> 0 lines break a limit
['--max-discount', '0.1']: max_quantity=50, max_discount=0.1 -> 1,439 lines break a limit

How it works:

  1. {**BUILT_IN, **from_file} starts with the built-in values and lets the file override them: max_quantity becomes 50 and max_discount 0.2.
  2. set_defaults() makes those merged values the parser’s defaults. A value on the command line still wins, because argparse uses a default only when the option is missing.
  3. With the config values, no line breaks a limit (the largest quantity is 25 and the largest discount 0.2). With --max-discount 0.1, every line with a 20% discount counts.
  4. count += too_many or discount_too_high adds 1 for True and 0 for False.

Alternative: read environment variables as a fourth layer between the file and the command line, for example os.environ.get("MAX_DISCOUNT"). Module 16 uses environment variables for secrets.

Challenge

Write the code: before a long training job starts, a check should prove that the environment matches the project’s pins. Write check_environment(requirements) that returns one status per pinned line: OK, MISMATCH (with both versions) or MISSING. Also report the Python version, whether it satisfies >=3.12, and whether a virtual environment is active. The starter list contains one wrong pin and one package that does not exist, on purpose.

Expected output
Python >=3.12: True
Virtual environment active: True
pandas OK
numpy MISMATCH (wanted 2.2.0, installed 2.5.4)
scikit-learn OK
notapackage MISSING
Ready to train: False
Starter
import sys
from importlib.metadata import PackageNotFoundError, version
REQUIREMENTS = [
"pandas==3.1.1",
"numpy==2.2.0",
"scikit-learn==1.9.1",
"notapackage==1.0",
]
def check_environment(requirements):
# TODO: return a list of (name, status) pairs
...
# TODO: print the Python check, the venv check and one line per requirement
# TODO: print a final verdict
Hint 1

name, wanted = line.split("==") splits a pin. version(name) raises PackageNotFoundError for a package that is not installed.

Hint 2

sys.version_info[:2] is a tuple such as (3, 13), and tuples compare item by item: (3, 13) >= (3, 12) is True.

Solution
import sys
from importlib.metadata import PackageNotFoundError, version
REQUIREMENTS = [
"pandas==3.1.1",
"numpy==2.2.0",
"scikit-learn==1.9.1",
"notapackage==1.0",
]
def check_environment(requirements):
"""Return (name, status) for every 'name==version' line."""
report = []
for line in requirements:
name, wanted = line.split("==")
try:
installed = version(name)
except PackageNotFoundError:
report.append((name, "MISSING"))
continue
if installed == wanted:
report.append((name, "OK"))
else:
report.append((name, f"MISMATCH (wanted {wanted}, installed {installed})"))
return report
python_ok = sys.version_info[:2] >= (3, 12)
print("Python >=3.12:", python_ok)
print("Virtual environment active:", sys.prefix != sys.base_prefix)
report = check_environment(REQUIREMENTS)
for name, status in report:
print(f" {name:<13} {status}")
problems = [name for name, status in report if status != "OK"]
print("Ready to train:", python_ok and not problems)
assert dict(report)["pandas"] == "OK"
assert dict(report)["notapackage"] == "MISSING"
assert dict(report)["numpy"].startswith("MISMATCH")
Output
Python >=3.12: True
Virtual environment active: True
pandas OK
numpy MISMATCH (wanted 2.2.0, installed 2.5.4)
scikit-learn OK
notapackage MISSING
Ready to train: False

How it works:

  1. Each pin splits into a name and the wanted version. version() gives the installed one, or raises PackageNotFoundError.
  2. A string comparison is enough for exact pins. For ranges, use packaging.specifiers.SpecifierSet as in exercise M08-C11.
  3. sys.version_info[:2] keeps the major and minor version, and tuple comparison checks >=3.12 correctly; a string comparison would put "3.9" above "3.12".
  4. The verdict is False because of the two planted problems. In a real check, main() would return exit code 1 so that a scheduler stops the job.

Alternative: uv sync --locked (or uv pip sync requirements.txt) does not just report differences, it fixes them. Run it before the job, and keep this check for environments that you cannot change.

M08-X04 · Fix the bugs: an end-to-end revenue filter

Section titled “M08-X04 · Fix the bugs: an end-to-end revenue filter”
Challenge

Fix the bugs: revenue_filter keeps the order lines of data/sales.csv with at least --min-revenue USD, groups them by --by, prints the --top groups and, with --share, their share of the filtered revenue. It returns exit code 1 when no line passes the filter, so a scheduler can react. The run() function has four bugs; each one appears only after you fix the previous one. Fix them, then run the three test calls of the starter.

Expected output
Electronics 1,808,108.17
Home 672,294.61
Sports 544,108.55
exit code: 0
East 456,459.41 29.2%
North 387,173.86 24.8%
South 366,924.21 23.5%
exit code: 0
No order lines pass the filter
exit code: 1
Starter
import argparse
import csv
def build_parser():
parser = argparse.ArgumentParser(prog="revenue_filter")
parser.add_argument("path")
parser.add_argument("--by", choices=["Category", "Region"], default="Category")
parser.add_argument("--min-revenue", type=float, default=0.0)
parser.add_argument("--share", type=bool, default=False)
parser.add_argument("--top", type=int, default=3)
return parser
def run(argv=None):
args = build_parser().parse_args()
totals = {}
with open(args.path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
revenue = float(row["revenue"])
if revenue >= args.min-revenue:
totals[row[args.by]] = totals.get(row[args.by], 0.0) + revenue
if not totals:
print("No order lines pass the filter")
return 1
filtered_total = sum(totals.values())
ranked = sorted(totals.items(), key=lambda item: item[1], reverse=True)
for group, revenue in ranked[: args.top]:
line = f"{group:<12} {revenue:>14,.2f}"
if args.share:
line += f" {revenue / filtered_total:6.1%}"
print(line)
return 0
print("exit code:", run(["data/sales.csv"]))
print("exit code:", run(["data/sales.csv", "--by", "region", "--min-revenue", "500", "--share"]))
print("exit code:", run(["data/sales.csv", "--min-revenue", "100000"]))
# TODO: fix the four bugs
Hint 1

The first call already fails with error: the following arguments are required: path, although the list contains a path. Which list does parse_args() read when you give it none?

Hint 2

Next come an invalid choice: 'region', an AttributeError: 'Namespace' object has no attribute 'min' and argument --share: expected one argument. Compare each one with the header of the CSV file and with the lesson’s pitfalls table.

Hint 3

The four fixes: pass argv on, use the lowercase column names as choices, write args.min_revenue, and make --share a store_true flag.

Solution
import argparse
import csv
def build_parser():
"""Return the parser of revenue_filter."""
parser = argparse.ArgumentParser(prog="revenue_filter")
parser.add_argument("path")
parser.add_argument("--by", choices=["category", "region"], default="category")
parser.add_argument("--min-revenue", type=float, default=0.0)
parser.add_argument("--share", action="store_true")
parser.add_argument("--top", type=int, default=3)
return parser
def run(argv=None):
"""Filter, group and print; return 0, or 1 when no line passes."""
args = build_parser().parse_args(argv)
totals = {}
with open(args.path, newline="", encoding="utf-8") as file:
for row in csv.DictReader(file):
revenue = float(row["revenue"])
if revenue >= args.min_revenue:
totals[row[args.by]] = totals.get(row[args.by], 0.0) + revenue
if not totals:
print("No order lines pass the filter")
return 1
filtered_total = sum(totals.values())
ranked = sorted(totals.items(), key=lambda item: item[1], reverse=True)
for group, revenue in ranked[: args.top]:
line = f"{group:<12} {revenue:>14,.2f}"
if args.share:
line += f" {revenue / filtered_total:6.1%}"
print(line)
return 0
big = ["data/sales.csv", "--by", "region", "--min-revenue", "500", "--share"]
codes = []
for argv in [["data/sales.csv"], big, ["data/sales.csv", "--min-revenue", "100000"]]:
codes.append(run(argv))
print("exit code:", codes[-1])
assert codes == [0, 0, 1]
assert build_parser().parse_args(["x.csv"]).share is False
Output
Electronics 1,808,108.17
Home 672,294.61
Sports 544,108.55
exit code: 0
East 456,459.41 29.2%
North 387,173.86 24.8%
South 366,924.21 23.5%
exit code: 0
No order lines pass the filter
exit code: 1

How it works:

  1. Bug 1, the ignored argv. parse_args() with no list reads sys.argv[1:], the real command line. In a test or a notebook that is empty or full of other words, so the path was “missing”. parse_args(argv) passes the test’s list on, and argv=None still reads the real command line when you run the file.
  2. Bug 2, the choices. choices compares strings exactly, and the CSV header uses category and region. With "Region", the user could never ask for the existing column; with the default "Category", row[args.by] raised KeyError.
  3. Bug 3, the dash. args.min-revenue is the subtraction args.min - revenue. argparse stores the option as args.min_revenue.
  4. Bug 4, the flag. type=bool makes --share take a value, and bool("False") would be True. action="store_true" makes a real flag.
  5. End to end. With no options, the report ranks all categories. Lines of 500 USD or more come mostly from electronics, so the regional shares are close to the overall ones. A threshold of 100,000 USD keeps no line, and run() returns 1: the exit code a scheduler would see through raise SystemExit(run()).

Alternative: test the parser alone first (build_parser().parse_args([...]) for each option), as in exercise M08-C02. Parser bugs then show up in a three-line test instead of in the middle of a data pipeline.

Challenge

Write the code: an automation tool, like uv init, creates new projects. Write make_skeleton(root, name) that writes a flat-layout project: pyproject.toml with the name, version 0.1.0, requires-python = ">=3.12" and an entry point, plus NAME/__init__.py, NAME/cli.py with an argparse main() and NAME/__main__.py. Then prove that it works: read the pyproject.toml back with tomllib and run python -m NAME --help in the new folder with subprocess. Create the project output/storecheck for a store checker.

Expected output
Files: ['pyproject.toml', 'storecheck/__init__.py', 'storecheck/__main__.py', 'storecheck/cli.py']
Project: storecheck 0.1.0 {'storecheck': 'storecheck.cli:main'}
Exit code: 0
usage: storecheck [-h] store_id
Check one store.
positional arguments:
store_id store id such as S01
options:
-h, --help show this help message and exit
Starter
import shutil
import subprocess
import sys
import tomllib
from pathlib import Path
PYPROJECT = '''\
[project]
name = "{name}"
...
'''
# TODO: templates for __init__.py, cli.py and __main__.py
def make_skeleton(root, name):
# TODO: create the folders and write the four files; return the file paths
...
root = Path("output/storecheck")
# TODO: delete root if it exists, make the skeleton, print the files
# TODO: read pyproject.toml back, run python -m storecheck --help in root
Hint 1

Write each template as a string with {name} placeholders and fill it with .format(name=name). A { that must stay in the file is written {{.

Hint 2

Path.mkdir(parents=True, exist_ok=True) creates nested folders. Path.write_text(text, encoding="utf-8") writes a file.

Hint 3

subprocess.run([sys.executable, "-m", name, "--help"], cwd=root, capture_output=True, text=True) runs the new package from its own folder, so the folder is on sys.path.

Solution
import shutil
import subprocess
import sys
import tomllib
from pathlib import Path
TEMPLATES = {
"pyproject.toml": """\
[project]
name = "{name}"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = []
[project.scripts]
{name} = "{name}.cli:main"
[build-system]
requires = ["hatchling>=1.27"]
build-backend = "hatchling.build"
""",
"{name}/__init__.py": '"""{name}: a generated package."""\n__version__ = "0.1.0"\n',
"{name}/__main__.py": "from .cli import main\n\nraise SystemExit(main())\n",
"{name}/cli.py": '''\
import argparse
def main(argv=None):
parser = argparse.ArgumentParser(prog="{name}", description="Check one store.")
parser.add_argument("store_id", help="store id such as S01")
parser.parse_args(argv)
return 0
''',
}
def make_skeleton(root, name):
"""Write a flat-layout project for package `name` into `root`."""
written = []
for template_path, template in TEMPLATES.items():
path = Path(root) / template_path.format(name=name)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(template.format(name=name), encoding="utf-8")
written.append(path.relative_to(root).as_posix())
return sorted(written)
root = Path("output/storecheck")
if root.exists():
shutil.rmtree(root)
files = make_skeleton(root, "storecheck")
print("Files:", files)
with open(root / "pyproject.toml", "rb") as file:
project = tomllib.load(file)["project"]
print("Project:", project["name"], project["version"], project["scripts"])
result = subprocess.run(
[sys.executable, "-m", "storecheck", "--help"],
cwd=root, capture_output=True, text=True,
)
print("Exit code:", result.returncode)
print(result.stdout.strip())
assert result.returncode == 0
assert files == ["pyproject.toml", "storecheck/__init__.py",
"storecheck/__main__.py", "storecheck/cli.py"]
Output
Files: ['pyproject.toml', 'storecheck/__init__.py', 'storecheck/__main__.py', 'storecheck/cli.py']
Project: storecheck 0.1.0 {'storecheck': 'storecheck.cli:main'}
Exit code: 0
usage: storecheck [-h] store_id
Check one store.
positional arguments:
store_id store id such as S01
options:
-h, --help show this help message and exit

How it works:

  1. Each template is a string with {name} placeholders. .format(name=name) fills them in the file paths and in the file contents.
  2. mkdir(parents=True, exist_ok=True) creates output/storecheck/storecheck/ in one call.
  3. Deleting the folder first makes the tool safe to run again. relative_to(root).as_posix() prints short paths with / on every system.
  4. tomllib proves that the generated pyproject.toml is valid TOML with the right fields.
  5. cwd=root runs the child Python in the new project folder, so python -m storecheck finds the package there. Exit code 0 and the help text prove that __main__.py, the relative import and the parser all work.

Alternative: uv init --package storecheck creates a similar skeleton with a src layout, a README and a Git repository. Generators such as cookiecutter fill whole template folders. A small script like this one is still useful for a team’s own conventions.