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:
- Work in your course folder, the one that holds
data/. Copy thesalesreport/folder of the lesson into it for the exercises that use the package. - 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.
- Run the script from the course folder, for example
python exercise.py. Compare your output with the expected output. - 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
Section titled “Warm-up”M08-W01 · Import in three ways
Section titled “M08-W01 · Import in three ways”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.
161.4640.365sales .csv# 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.csvHint 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 mathimport statistics as stfrom 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"161.4640.365sales .csvHow it works:
import mathbinds the namemath; you reach its functions with a dot.import statistics as stbinds the same module object under the shorter namest.from pathlib import Pathbinds onlyPath, so you writePath(...)without a prefix.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”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.
import csv as tableimport json
print(__name__)print(json.__name__)print(table.__name__)print(table is __import__("csv"))# TODO: write your prediction for each line before you run itHint 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 tableimport json
print(__name__)print(json.__name__)print(table.__name__)print(table is __import__("csv"))assert __name__ == "__main__"assert table.__name__ == "csv"__main__jsoncsvTrueHow it works:
- The file that you run is the main module, so its
__name__is"__main__". - An imported module’s
__name__is its module name,"json". as tablechanges only the name in your namespace. The module still calls itselfcsv.- A module is loaded once. Every later import returns the same object from
sys.modules, soisgivesTrue.
M08-W03 · Fix the bug: a module that cannot be found
Section titled “M08-W03 · Fix the bug: a module that cannot be found”Fix the bug: this script must print whether the sales file exists and its name. It stops with ModuleNotFoundError: No module named 'Pathlib'.
True sales.csvfrom Pathlib import Path
sales = Path("data/sales.csv")print(sales.exists(), sales.name)# TODO: fix the importHint 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()True sales.csvHow it works:
- Python searched every folder of
sys.pathforPathliband found nothing, because the module is calledpathlib. - The class inside it is
Pathwith a capital P. Classes use CapWords names, modules use lowercase names (PEP 8). exists()isTruewhen you run the script from the course folder, which holdsdata/.
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.
M08-W04 · Add a main guard
Section titled “M08-W04 · Add a main guard”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.
Self-test: 21.5 °C is 70.7 °FImported units without side effects"""units.py: temperature conversions for sensor readings."""
def to_fahrenheit(celsius): """Return the temperature in °F.""" return celsius * 9 / 5 + 32
reading = 21.5print(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.pyHint 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: 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()Self-test: 21.5 °C is 70.7 °F"""check_import.py: importing units must print nothing."""
import units
assert units.to_fahrenheit(0) == 32print("Imported", units.__name__, "without side effects")Imported units without side effectsHow it works:
python units.pyruns the file as__main__, so the guard is true andmain()prints the self-test.import unitsruns the same file with__name__ == "units". The guard is false: the import definesto_fahrenheitandmainand prints nothing.- Only
check_import.py’s ownprint()appears.
M08-W05 · A positional argument and an option
Section titled “M08-W05 · A positional argument and an option”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.
data/sales.csv 5data/sales.csv 3import 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.topHint 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 == 5assert parser.parse_args(["x.csv", "--top", "3"]).top == 3data/sales.csv 5data/sales.csv 3How it works:
pathhas no dashes, so it is positional and required.--topis optional. Without it, argparse uses the default 5.type=intconverts 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”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.
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 itHint 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.0assert args.verbose is False100.0 online Falsefloat{'min_revenue': 100.0, 'channel': 'online', 'verbose': False}How it works:
type=floatconverts the text"100"to100.0."online"is one of the choices, so argparse accepts it.--verboseis missing, so the flag isFalse.vars()shows the Namespace as a dict, in the order of theadd_argument()calls. The key ismin_revenue, with an underscore.
M08-W07 · Read one command-line argument
Section titled “M08-W07 · Read one command-line argument”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.
Arguments: ['S05']Store S05 is in Atlantaimport csvimport 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 sentenceHint 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: print the city of the store named on the command line."""
import csvimport 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 citiesArguments: ['S05']Store S05 is in AtlantaHow it works:
python store_city.py S05puts["store_city.py", "S05"]intosys.argv, sosys.argv[1:]is["S05"].- The conditional expression picks the argument when there is one and the default otherwise. Without the length check,
sys.argv[1]raisesIndexErrorwhen you run the script with no argument. - 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.
M08-W08 · Am I in a virtual environment?
Section titled “M08-W08 · Am I in a virtual environment?”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.
Environment: .venvInside a virtual environment: Trueimport sysfrom 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 sysfrom 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()Environment: .venvInside a virtual environment: TrueHow it works:
- Inside a virtual environment,
sys.prefixpoints to the environment folder andsys.base_prefixto the base Python. Outside one, both are the same folder. - 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”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:
P001 Wireless Earbuds 79.99 -> 63.99P002 Noise-Cancelling Headphones 249.00 -> 199.20P006 Espresso Machine 349.00 -> 279.20# discounts.pyRATES = [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 discountsPRODUCTS = { "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 productHint 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: 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() 0% off: 249.00 USD 5% off: 236.55 USD 10% off: 224.10 USD 20% off: 199.20 USD"""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.0assert discounts.__name__ == "discounts"P001 Wireless Earbuds 79.99 -> 63.99P002 Noise-Cancelling Headphones 249.00 -> 199.20P006 Espresso Machine 349.00 -> 279.20How it works:
python discounts.pyruns the module as__main__, somain()prints the four prices.import discountsinprice_list.pyloads the same file as the modulediscounts. The guard is false, so the table of prices does not appear.price_list.pyuses only the function. The formula lives in one place; a fix there fixes every script.- 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.
M08-C02 · The parser of a sales report
Section titled “M08-C02 · The parser of a sales report”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.
{'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}import argparsefrom 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 textHint 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 argparsefrom 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{'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:
- The first list gives only the path, so every option takes its default.
--yearhas no default, so it isNone. - Options and the positional can come in any order: the third list puts the flag and
--yearfirst. type=Pathandtype=intconvert the text before your code sees it.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”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.
0.1 -> 0.10 -> 0.00.75 -> error: rate must be in [0, 0.5], got 0.75-0.2 -> error: rate must be in [0, 0.5], got -0.20.20.0import 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.0Hint 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.50.1 -> 0.10 -> 0.00.75 -> error: rate must be in [0, 0.5], got 0.75-0.2 -> error: rate must be in [0, 0.5], got -0.20.20.0How it works:
float(text)converts the string. Bad text such as"ten"raisesValueError, and argparse reports it asinvalid discount_rate value: 'ten'.- The range check raises
ArgumentTypeErrorwith a clear message. argparse prints it aftererror: argument --discount:and exits with code 2. - Because
discount_rateis 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”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.
55-inch 4K Smart TV 327,283.0514-inch Ultrabook Laptop 307,472.40Espresso Machine 11,656.60import argparseimport 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, repeatHint 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 argparseimport 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"55-inch 4K Smart TV 327,283.0514-inch Ultrabook Laptop 307,472.40Espresso Machine 11,656.60How it works:
- Bug 1, the year.
type=intwas right for--year: a year is a number, and argparse rejects--year 20x3. Butstr.startswith()needs text, so the comparison converts back withstr(args.year). - Bug 2, the minimum revenue. Without
type,args.min_revenueis the string"1000", andrevenue >= "1000"raisesTypeError: '>=' not supported between instances of 'float' and 'str'.type=floatwith the float default0.0fixes it. - Bug 3, the top count. Without
type, a value typed on the command line is a string, and a slice needs an int.type=intfixes it. (argparse converts a string default withtypetoo, but an int default says what you mean.) - Each bug shows only after the previous one is fixed, because Python stops at the first error. Read the last traceback line every time.
- The result: two large electronics products earn almost all big-line revenue. The third product is far behind.
M08-C05 · Use the salesreport package
Section titled “M08-C05 · Use the salesreport package”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.
2024: 11,147 lines, 1,950,934.24 USDElectronics 939,924.77 48.2%Home 397,844.84 20.4%Sports 299,576.31 15.4%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 shareHint 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_147assert all(row["order_date"].startswith("2024") for row in rows)2024: 11,147 lines, 1,950,934.24 USDElectronics 939,924.77 48.2%Home 397,844.84 20.4%Sports 299,576.31 15.4%How it works:
- The
salesreport/folder sits in the current folder, which is onsys.path, so the import works without an install. __init__.pyoffers the four functions at the top level, so onefrom salesreport import ...line is enough.- 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”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.
Sales report: 8,495 order lines, revenue 1,519,466.47 USDTop 3 by category: 1. Electronics 767,072.48 2. Home 284,066.00 3. Sports 226,771.66from salesreport import load_salesfrom 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_salesfrom 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")Sales report: 8,495 order lines, revenue 1,519,466.47 USDTop 3 by category: 1. Electronics 767,072.48 2. Home 284,066.00 3. Sports 226,771.66How it works:
- The package already has a tested parser, so
run()adds one option instead of copying the others. format_report()takes any list of rows, so it works on the filtered list unchanged.- 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.
M08-C07 · Read a pyproject.toml
Section titled “M08-C07 · Read a pyproject.toml”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.
churn-model 1.2.0 needs Python >=3.12 pandas >=3.1,<4 scikit-learn ~=1.9 joblib >=1.4command churn-train -> churn_model.train:maincommand churn-predict -> churn_model.predict:mainimport 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 fieldsHint 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"]) == 2churn-model 1.2.0 needs Python >=3.12 pandas >=3.1,<4 scikit-learn ~=1.9 joblib >=1.4command churn-train -> churn_model.train:maincommand churn-predict -> churn_model.predict:mainHow it works:
tomllib.loads()returns nested dicts:config["project"]["scripts"]is the[project.scripts]table.split_requirement()finds the first operator character and splits there.- 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.
M08-C08 · Audit a requirements file
Section titled “M08-C08 · Audit a requirements file”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.
Requirements: 7Not pinned: ['matplotlib>=3.11', 'scikit-learn~=1.9', 'pyyaml', 'joblib==1.6.*']Fully pinned: FalseREQUIREMENTS = """\# Analysis of data/sales.csvpandas==3.1.1numpy==2.5.4matplotlib>=3.11
scikit-learn~=1.9pyyamljoblib==1.6.*tzdata==2026.6 ; sys_platform == "win32""""
# TODO: skip blank lines and comments# TODO: count requirements, list the unpinned ones, print the verdictHint 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.csvpandas==3.1.1numpy==2.5.4matplotlib>=3.11
scikit-learn~=1.9pyyamljoblib==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) == 7assert unpinned == ["matplotlib>=3.11", "scikit-learn~=1.9", "pyyaml", "joblib==1.6.*"]Requirements: 7Not pinned: ['matplotlib>=3.11', 'scikit-learn~=1.9', 'pyyaml', 'joblib==1.6.*']Fully pinned: FalseHow it works:
- Comments and blank lines are not requirements, so the loop skips them.
- The marker after
;is a condition, not part of the version.split(";")[0]drops it before the test. matplotlib>=3.11andscikit-learn~=1.9are ranges;pyyamlaccepts any version.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*.- The file is not reproducible until all four are pinned, for example with
uv pip compile.
M08-C09 · Find files that shadow modules
Section titled “M08-C09 · Find files that shadow modules”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.
Rename these files: ['email', 'pandas', 'random', 'statistics']import sysfrom 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 resultHint 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 sysfrom 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) == []Rename these files: ['email', 'pandas', 'random', 'statistics']How it works:
- The script folder comes first in
sys.path, so each of these files wins over the real module. email.pyis a surprise for many people:emailis a standard library package, and other standard modules import it:http.clientdoes, sourllib.requestbreaks too.notes.txtis 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”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.
by path: exit 1: ImportError: attempted relative import with no known parent packagewith -m: exit 0: 1. Electronics 1,808,108.17import subprocessimport 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 subprocessimport 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}by path: exit 1: ImportError: attempted relative import with no known parent packagewith -m: exit 0: 1. Electronics 1,808,108.17How it works:
sys.executableis the path of the Python that runs this script, so both commands use the same environment.- By path,
cli.pyruns as a lone script with no parent package. Its first relative import,from . import __version__, fails, and an uncaught exception gives exit code 1. - With
-m, Python imports the packagesalesreportfirst and runs__main__.py, so every relative import has a parent. The report runs andmain()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”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.
- A library you publish needs pandas 3.1 or newer, and you have not tested pandas 4.
- A team analysis must use exactly the pandas the results were produced with.
- You accept bug-fix releases of scikit-learn 1.9 only.
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: Truescikit-learn~=1.9.0 accepts 1.9.1: Truescikit-learn~=1.9.0 accepts 1.10.0: Falsefrom 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"]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: Truescikit-learn~=1.9.0 accepts 1.9.1: Truescikit-learn~=1.9.0 accepts 1.10.0: FalseHow it works and why:
- 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. - 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’sdependencies. - Bug fixes only:
~=1.9.0. It allows 1.9.1 and rejects 1.10.0. Note that~=1.9would 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”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.
S07 204,366.16S10 188,144.28import 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 guardHint 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 argparseimport 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 == 0assert len(top_stores("data/sales.csv", 2024, 4)) == 4S07 204,366.16S10 188,144.28How it works:
- Each hard-coded constant became an argument with a default, so the old behavior is one command away.
top_stores()returns data. A test, a notebook or another module can now use it.main(argv=None)reads the real command line when you run the file, and a list when a test calls it.- 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__":andmain(), and runpython top_stores.py data/sales.csv --year 2023 --top 2.
M08-C13 · Pin what a project imports
Section titled “M08-C13 · Pin what a project imports”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.
matplotlib==3.11.2pandas==3.1.1PyYAML==6.0.3scikit-learn==1.9.1from 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-insensitivelyHint 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 distributionsassert all("==" in pin for pin in pins)matplotlib==3.11.2pandas==3.1.1PyYAML==6.0.3scikit-learn==1.9.1How it works:
- The import name and the distribution name differ for two of the four:
sklearncomes fromscikit-learnandyamlfromPyYAML. version()takes the distribution name and reads the installed version.- 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.
M08-C14 · Fix the bug: a circular import
Section titled “M08-C14 · Fix the bug: a circular import”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:
cd exercises/c14_broken && python report.py 2>&1 | tail -n 1 | cut -d "(" -f 1-2 | fold -s -w 90ImportError: 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.
Mean line revenue: 177.80 USD"""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)]"""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)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.pyHint 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.
"""settings.py: shared constants; imports nothing from the package."""
REVENUE_COLUMN = "revenue"SALES_PATH = "data/sales.csv""""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)]"""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: print the mean line revenue."""
from salesmini.settings import SALES_PATHfrom salesmini.stats import mean_revenue
mean = mean_revenue(SALES_PATH)print(f"Mean line revenue: {mean:.2f} USD")assert round(mean, 2) == 177.80Mean line revenue: 177.80 USDHow it works:
reportimportssalesmini.stats. Python starts to runstats.pyand puts the half-finished module intosys.modules.- The first line of
stats.pyimportsloader, whose first line asksstatsforREVENUE_COLUMN.statsstopped at its first line, so the name does not exist yet: “partially initialized module”. settings.pyimports nothing from the package, so it is always complete when another module needs it.loaderdepends onsettings,statsdepends onloader, and nothing points back.- 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
Section titled “Challenge”M08-X01 · A CLI with subcommands
Section titled “M08-X01 · A CLI with subcommands”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.
20,228 lines, 3,596,523.83 USDEast 993,683.72South 891,766.07import 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"20,228 lines, 3,596,523.83 USDEast 993,683.72South 891,766.07How it works:
add_subparsers()adds a special positional argument: the subcommand name.dest="command"stores it inargs.command.- Each subcommand is a parser of its own, so
tophas--byand--topandsummarydoes not. set_defaults(func=...)puts a function into the Namespace.main()does not need anif/elifchain to dispatch.python salescli.py --helplists the subcommands;python salescli.py top --helpshows the options oftop.
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”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.
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 limitimport argparseimport csvimport 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 argparseimport csvimport 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"] == 50assert results[0] == 0 and results[1] > 0Built-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 limitHow it works:
{**BUILT_IN, **from_file}starts with the built-in values and lets the file override them:max_quantitybecomes 50 andmax_discount0.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.- 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. count += too_many or discount_too_highadds 1 forTrueand 0 forFalse.
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.
M08-X03 · An environment doctor
Section titled “M08-X03 · An environment doctor”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.
Python >=3.12: TrueVirtual environment active: True pandas OK numpy MISMATCH (wanted 2.2.0, installed 2.5.4) scikit-learn OK notapackage MISSINGReady to train: Falseimport sysfrom 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 verdictHint 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 sysfrom 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")Python >=3.12: TrueVirtual environment active: True pandas OK numpy MISMATCH (wanted 2.2.0, installed 2.5.4) scikit-learn OK notapackage MISSINGReady to train: FalseHow it works:
- Each pin splits into a name and the wanted version.
version()gives the installed one, or raisesPackageNotFoundError. - A string comparison is enough for exact pins. For ranges, use
packaging.specifiers.SpecifierSetas in exercise M08-C11. sys.version_info[:2]keeps the major and minor version, and tuple comparison checks>=3.12correctly; a string comparison would put"3.9"above"3.12".- The verdict is
Falsebecause 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”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.
Electronics 1,808,108.17Home 672,294.61Sports 544,108.55exit code: 0East 456,459.41 29.2%North 387,173.86 24.8%South 366,924.21 23.5%exit code: 0No order lines pass the filterexit code: 1import argparseimport 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 bugsHint 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 argparseimport 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 FalseElectronics 1,808,108.17Home 672,294.61Sports 544,108.55exit code: 0East 456,459.41 29.2%North 387,173.86 24.8%South 366,924.21 23.5%exit code: 0No order lines pass the filterexit code: 1How it works:
- Bug 1, the ignored argv.
parse_args()with no list readssys.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, andargv=Nonestill reads the real command line when you run the file. - Bug 2, the choices.
choicescompares strings exactly, and the CSV header usescategoryandregion. With"Region", the user could never ask for the existing column; with the default"Category",row[args.by]raisedKeyError. - Bug 3, the dash.
args.min-revenueis the subtractionargs.min - revenue. argparse stores the option asargs.min_revenue. - Bug 4, the flag.
type=boolmakes--sharetake a value, andbool("False")would beTrue.action="store_true"makes a real flag. - 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 throughraise 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.
M08-X05 · Generate a project skeleton
Section titled “M08-X05 · Generate a project skeleton”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.
Files: ['pyproject.toml', 'storecheck/__init__.py', 'storecheck/__main__.py', 'storecheck/cli.py']Project: storecheck 0.1.0 {'storecheck': 'storecheck.cli:main'}Exit code: 0usage: storecheck [-h] store_id
Check one store.
positional arguments: store_id store id such as S01
options: -h, --help show this help message and exitimport shutilimport subprocessimport sysimport tomllibfrom 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 rootHint 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 shutilimport subprocessimport sysimport tomllibfrom 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 == 0assert files == ["pyproject.toml", "storecheck/__init__.py", "storecheck/__main__.py", "storecheck/cli.py"]Files: ['pyproject.toml', 'storecheck/__init__.py', 'storecheck/__main__.py', 'storecheck/cli.py']Project: storecheck 0.1.0 {'storecheck': 'storecheck.cli:main'}Exit code: 0usage: storecheck [-h] store_id
Check one store.
positional arguments: store_id store id such as S01
options: -h, --help show this help message and exitHow it works:
- Each template is a string with
{name}placeholders..format(name=name)fills them in the file paths and in the file contents. mkdir(parents=True, exist_ok=True)createsoutput/storecheck/storecheck/in one call.- Deleting the folder first makes the tool safe to run again.
relative_to(root).as_posix()prints short paths with/on every system. tomllibproves that the generatedpyproject.tomlis valid TOML with the right fields.cwd=rootruns the child Python in the new project folder, sopython -m storecheckfinds 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.