Python Master Course V2 — 070. Modules and Packaging Capstone
SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 07 — MODULES AND PACKAGES · LESSON 070 / 200
Modules and Packaging Capstone
Estimated study: 60–90 minutes. Prerequisites: functions, collections, control flow and the preceding lesson. Level: intermediate Python.
Video lesson
Video not yet available. Reserved for a verified video URL/player; written learning materials are available now.
Learning outcomes
Integrate modular design and reproducible setup. After completing this lesson, you should be able to explain the underlying mechanism, run the example, identify a boundary case, and apply the concept in a practical program.
Understand Modules and Packaging Capstone
Deliver a package that can be installed elsewhere
The capstone turns the expense calculator into an installable project. Its core contract uses nonnegative integer cents, avoiding binary floating-point rounding in this small exercise. An empty iterable totals zero; booleans, negative values and non-integers are rejected. Keep the existing Decimal summation as a separate warmup if desired, but do not mix cents and currency-unit Decimals in one API without an explicit conversion boundary.
Use a src layout so running from the repository root does not accidentally make an uninstalled source package look installed. The distribution name expensekit-demo is used by installation tools; the Python import name is expensekit. Their spellings need not match. The version belongs in project metadata. This exercise builds and installs locally; it does not require creating an account or publishing anything to a public registry.
expense-project/
pyproject.toml
README.md
src/
expensekit/
__init__.py
totals.py
cli.py
__main__.py
tests/
test_totals.py
[build-system]
requires = ["setuptools"]
build-backend = "setuptools.build_meta"
[project]
name = "expensekit-demo"
version = "0.1.0"
description = "A teaching calculator for integer-cent expenses"
requires-python = ">=3.10"
readme = "README.md"
dependencies = []
[project.scripts]
expense-total = "expensekit.cli:main"
[tool.setuptools.packages.find]
where = ["src"]
def total_cents(amounts):
"""Sum nonnegative integer cents; reject other values."""
total = 0
for amount in amounts:
if type(amount) is not int or amount < 0:
raise ValueError("amounts must be nonnegative integer cents")
total += amount
return total
import argparse
from .totals import total_cents
def main(argv=None):
parser = argparse.ArgumentParser(description="Add expense amounts in cents")
parser.add_argument("amounts", nargs="*", type=int)
args = parser.parse_args(argv)
try:
result = total_cents(args.amounts)
except ValueError as error:
parser.error(str(error))
print(result)
return 0
from .cli import main
if __name__ == "__main__":
raise SystemExit(main())
Leave __init__.py empty. In README.md, state the cents-based input contract, supported Python version, setup commands, test command and example output. The console-script declaration asks installation tooling to create an expense-total launcher calling main. __main__.py separately supports python -m expensekit. Both interfaces use the same CLI function, so behavior does not drift between entry points.
import unittest
from expensekit.totals import total_cents
class TotalTests(unittest.TestCase):
def test_total(self):
self.assertEqual(total_cents([550, 225]), 775)
def test_empty(self):
self.assertEqual(total_cents([]), 0)
def test_invalid(self):
for value in (-1, True, 1.5, "200"):
with self.subTest(value=value):
with self.assertRaises(ValueError):
total_cents([value])
if __name__ == "__main__":
unittest.main()
Install, test, build and verify the built artifact
Create and activate a disposable .venv using Lesson 066, then run these commands from expense-project. Editable installation lets imports use the working source during development. The build frontend creates a wheel and source distribution in dist; a wheel is the installable artifact used for the clean-environment check. Build and installation logs vary by tool versions and platform, so focus on successful exits and the explicit behavior checks.
python -m pip install -e .
python -m unittest discover -s tests
python -m expensekit 550 225
python -m pip install build
python -m build
775
The 775 output belongs to the expensekit command; unittest reports three tests and an OK summary when they pass. Do not claim success until those commands actually finish. Next install the newly built wheel into a different environment, using its real filename if your build configuration changes. The -I flag ignores the working directory and user site for the smoke check, helping confirm that the installed artifact supplies the import.
python3 -m venv .verify
.verify/bin/python -m pip install dist/expensekit_demo-0.1.0-py3-none-any.whl
.verify/bin/python -m unittest discover -s tests
.verify/bin/python -I -m expensekit 550 225
py -3 -m venv .verify
.verify\Scripts\python.exe -m pip install dist/expensekit_demo-0.1.0-py3-none-any.whl
.verify\Scripts\python.exe -m unittest discover -s tests
.verify\Scripts\python.exe -I -m expensekit 550 225
775
The finished deliverable includes source, metadata, README and tests, plus a wheel verified in the clean environment. Re-run the tests against that installed environment and try empty and negative CLI inputs. Keep generated environments and build outputs separate from authored source. The Python Packaging User Guide explains build metadata and artifact creation; the commands here intentionally stop before any public upload.
Arithmetic warmup: Decimal currency units
This original calculation is independent of the integer-cent packaging API above; do not combine their units implicitly.
Requires Python 3.10+. Save the example as lesson70.py and run python lesson70.py (or python3). If it writes a file, run it in a disposable practice directory.
from decimal import Decimal
def total(prices):
return sum(prices, Decimal('0'))
print(total([Decimal('5.50'), Decimal('2.25')]))
Expected output:
7.75
Step-by-step walkthrough
Read each statement in execution order. Identify imported modules, assigned variables, functions and the result passed to print(). Compare the output with the expected output and then change one input. Explain why the behavior changed. When an exception occurs, read the final traceback line and inspect the call that produced it.
Extension example
Refactor the central calculation or operation into a named function with a docstring and type hints. Add a caller that invokes it twice with different inputs. Test both results with assertions; for file operations, also test that the expected file exists and clean up practice files afterward.
Guided project — Modules and Packaging Capstone application
Deliver a packaged expense calculator with README and unit tests.
- Write a short requirements document specifying input data, output data and expected errors.
- Implement one focused function or module for the core behavior.
- Write a separate program entry point to collect or construct example input.
- Add validation and informative errors where appropriate.
- Test a normal case, a boundary case and an invalid case.
- Write a README showing how to run and test the program.
Acceptance criteria: clear behavior, no unexplained dependencies, reproducible execution and a documented result. The project is a guided assignment; its implementation must be completed and tested by the learner.
Common mistakes, debugging and best practices
- Importing a local file with the same name as a standard-library module, causing shadowing.
- Using broad exception handlers that conceal the real defect.
- Assuming a path or dependency exists on every computer.
- Mixing input/output and reusable business logic into one difficult-to-test function.
- Testing only the happy path rather than edge cases and failures.
Debugging procedure: reproduce the failure with the smallest input; read the traceback; verify assumptions and data types; change one thing; rerun the same test; add a regression test after the fix.
Practice and explained answers
Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.
Optional hint for question 1
Consider whether the repository root should make an uninstalled package importable.
1. Why use a src layout?
Answer and reasoning:
It reduces accidental imports from the repository root and encourages testing the installed package. A project that only works because its source directory happens to be on the import path is not yet a reliable distribution.
2. Are expensekit-demo and expensekit the same kind of name?
Answer and reasoning:
No. expensekit-demo is the distribution name in metadata and installation commands. expensekit is the import package name. Packaging tools connect the installed distribution to its contained importable files.
3. What does an editable install prove, and what does it not prove?
Answer and reasoning:
It lets development code be imported through the environment and supports rapid editing. It does not prove the built wheel contains all required files. Install the wheel into a clean environment and run it there.
4. Why test True as an invalid amount?
Answer and reasoning:
True is an int subclass and could otherwise be silently counted as one cent. The explicit plain-integer contract rejects it, making accidental booleans visible.
5. What are the acceptance results for ordinary, empty and invalid inputs?
Answer and reasoning:
550 and 225 produce 775. No amounts produce 0. A negative amount is rejected with an argument error and a nonzero exit status. Unit tests also reject floats, strings and booleans at the core API boundary. Preserve those checks when changing the packaging configuration.
Knowledge check
Use the topic-specific practice questions above to check your understanding. Attempt each answer before opening its explanation.
Mastery checkpoint and summary
Demonstrate the concept without copying, explain one failure mode, complete the guided project and write three independent tests. These are suggested mastery checks, not account-synchronized completion records.
Key takeaway: Integrate modular design and reproducible setup. Apply it through clear contracts, thoughtful error handling, and repeatable testing.
Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.