PCAP Python Project: Build a Multi-Module Inventory Report
Introduction
This PCAP Python project opens chapter 14, the integration chapter of the course. It combines familiar Python syntax in a multi-module inventory report, joining the five skill areas of PCAP-31-03 in one realistic program: Modules and Packages (12% of the score, 6 of 40 items), Exceptions (14%, 5 items), Strings (18%, 8 items), Object-Oriented Programming (34%, 12 items) and Comprehensions, Lambdas, Closures, and I/O (22%, 9 items). A single practice code sample can need an import rule, a class mechanism, a string method and an exception rule at the same time, so you must be able to switch between them while reading.
You will follow a small inventory program from its folder layout to its report file, and at each step you will name the objective that explains what happens. By the end you can trace a multi-file program in the order Python executes it, which is the skill that turns many exam items from guesses into deductions.
Learning objectives
After this lesson you can:
- Predict the order of output when a package, its submodules and a main script are imported and run.
- Explain the effect of
__name__,__all__, relative imports andsys.modulesin a concrete package. - Design a small exception hierarchy and choose where to catch each class.
- Read a class hierarchy with a class attribute, a name-mangled attribute, a property and
super(), and predict the instance state. - Parse and format text with
split,strip, f-strings and encodings, and relate characters to bytes. - Combine a comprehension, a lambda, a closure and a text or binary file in one pipeline.
- Use a systematic reading order to trace an unfamiliar program.
The project
A small shop keeps its stock in a UTF-8 text file with one item per line: name,quantity,price, or name,quantity,price,days for perishable goods. The program must load the file, skip damaged lines while remembering their numbers, build objects, filter and sort them, and write a short report. Run this exercise in a disposable project folder: the script overwrites stock.csv and report.txt in its current working directory. This simplified CSV parser assumes that fields contain no commas or quoted records; it checks field count and numeric conversion, not business rules such as non-negative prices. A production inventory also needs a CSV parser, validation and decimal arithmetic for money.
The layout is:
project/
main.py
inventory/
__init__.py
errors.py
models.py
parsing.py
report.pyHere inventory is a regular package containing __init__.py. Its first successful import executes this file; subsequent ordinary imports reuse the cached module. Namespace packages can exist without __init__.py. Here it prints a message and defines __all__:
# inventory/__init__.py
print("loading inventory")
__all__ = ["errors", "models"]The module errors.py defines the exceptions of the domain:
# inventory/errors.py
class InventoryError(Exception):
"""Base class for domain errors."""
class ParseError(InventoryError):
def __init__(self, line_no, text):
super().__init__(f"line {line_no}: {text!r}")
self.line_no = line_noThe module models.py holds the classes:
# inventory/models.py
class Item:
count = 0
def __init__(self, name, qty, price):
self.name = name
self.qty = qty
self.__price = price
Item.count += 1
@property
def value(self):
return self.qty * self.__price
def label(self):
return f"{self.name} x{self.qty}"
def __str__(self):
return self.label()
class Perishable(Item):
def __init__(self, name, qty, price, days):
super().__init__(name, qty, price)
self.days = days
def label(self):
return super().label() + f" ({self.days}d)"The module parsing.py turns a line into an object:
# inventory/parsing.py
from .errors import ParseError
from .models import Item, Perishable
def parse_line(line_no, text):
parts = text.strip().split(",")
try:
if len(parts) == 3:
return Item(parts[0], int(parts[1]), float(parts[2]))
if len(parts) == 4:
return Perishable(parts[0], int(parts[1]), float(parts[2]), int(parts[3]))
except ValueError as exc:
raise ParseError(line_no, text.strip()) from exc
raise ParseError(line_no, text.strip())The module report.py contains a closure factory and a dictionary comprehension:
# inventory/report.py
def make_filter(minimum):
def keep(item):
return item.value >= minimum
return keep
def summarize(items):
return {item.name: item.value for item in items}Finally main.py ties everything together:
import sys
from inventory import models
from inventory.parsing import parse_line
from inventory.errors import InventoryError, ParseError
from inventory.report import make_filter, summarize
print(__name__, models.__name__, sys.modules["inventory"].__all__)
with open("stock.csv", "w", encoding="utf-8") as f:
f.write("café,12,1.5\nmilk,7,0.9,5\nbad,x,2\ntea,5\n")
items, errors = [], []
with open("stock.csv", encoding="utf-8") as f:
for no, line in enumerate(f, 1):
try:
items.append(parse_line(no, line))
except ParseError as e:
errors.append(e.line_no)
except InventoryError:
print("other")
print([str(i) for i in items], errors, models.Item.count)
keep = make_filter(10)
big = [i.name for i in items if keep(i)]
ordered = sorted(items, key=lambda i: -i.value)
print(big, [i.name for i in ordered], summarize(items))
print(isinstance(items[1], models.Item), hasattr(items[0], "_Item__price"), hasattr(items[0], "days"))
print(items[1].__dict__)
with open("report.txt", "wb") as r:
n = r.write("\n".join(f"{i.name}:{i.value:.2f}" for i in items).encode("utf-8"))
with open("report.txt", "rb") as r:
raw = r.read()
print(n, raw)Running python main.py from the project folder prints:
loading inventory
__main__ inventory.models ['errors', 'models']
['café x12', 'milk x7 (5d)'] [3, 4] 2
['café'] ['café', 'milk'] {'café': 18.0, 'milk': 6.3}
True True False
{'name': 'milk', 'qty': 7, '_Item__price': 0.9, 'days': 5}
21 b'caf\xc3\xa9:18.00\nmilk:6.30'The rest of the lesson explains each line. Read it as a model of how you should reason in the exam.
Reading order: from imports to output
A reliable method for a multi-file sample has five passes.
- Imports first. Which modules are executed, in which order, and what do they print or define at import time?
- Definitions. A
defstatement creates a function without running its function body. Aclassstatement executes the class body immediately, including class-attribute assignments and method definitions; method bodies wait until they are called. - Calls in order. Follow the top-level statements one at a time.
- State. Keep a small table of variables and attributes, and update it after each statement.
- Exceptions. When a statement raises, find the first matching
exceptclause, and note what is skipped.
Apply this to main.py.
Pass 1: imports (objectives 1.1 to 1.5)
from inventory import models is the first import. Python looks in sys.modules; inventory is absent, so it finds the folder, executes inventory/__init__.py and prints loading inventory. It then imports the submodule inventory.models, which defines the classes silently. The statement binds only the name models in main; the name inventory itself is not bound by this form of import, which is why the program later reaches the package through sys.modules["inventory"].
The next imports reuse the cached package, so loading inventory is not printed again. inventory.parsing runs from .errors import ParseError: the dot is a relative import meaning "from the same package". Python imports inventory.errors first, then inventory.models, which is already loaded. Importing inventory.errors in main later finds the module in sys.modules.
| Import form | Names bound in main |
Runs the module? |
|---|---|---|
from inventory import models |
models |
Package once, submodule once |
from inventory.parsing import parse_line |
parse_line |
Only if not yet loaded |
import inventory.errors (not used here) |
inventory |
Only if not yet loaded |
from inventory.errors import * (not used) |
Names allowed by that module's __all__, if any |
Only if not yet loaded |
The first printed line of main.py, __main__ inventory.models ['errors', 'models'], shows three facts. The script itself has __name__ equal to '__main__'. The imported module has its qualified name inventory.models. And __all__ of the package is a list of strings that controls what from inventory import * would import, which here are the two submodules.
Exam tip. __all__ controls wildcard exports from modules as well as packages. It does not hide anything from an explicit import such as from inventory import models.
Pass 2: exceptions (objectives 2.1 and 2.2)
ParseError derives from InventoryError, which derives from Exception. The order of except clauses in main.py is intentional: the specific class ParseError is first and its parent InventoryError second. If the order were reversed, the parent would catch every ParseError and the specific branch would never run.
Now trace the four lines of stock.csv:
| Line | Text | Path through parse_line |
Result |
|---|---|---|---|
| 1 | café,12,1.5 |
3 parts, int("12") and float("1.5") succeed |
Item |
| 2 | milk,7,0.9,5 |
4 parts, all conversions succeed | Perishable |
| 3 | bad,x,2 |
3 parts, int("x") raises ValueError, converted to ParseError(3, ...) |
skipped, line 3 recorded |
| 4 | tea,5 |
2 parts, no if matches, falls to the final raise |
ParseError(4, ...), line 4 recorded |
Two details matter. First, raise ... from exc stores the original ValueError in __cause__ of the new exception, so the history is preserved. Second, the try block in parse_line covers only the conversions that can fail. The final raise ParseError is outside it, because a wrong number of fields is not a ValueError; keeping the try narrow avoids catching exceptions that you did not expect.
Notice the counter. Item.count is 2, not 4. For line 3, int("x") fails while the arguments of Item(...) are being evaluated, so the constructor is never called. For line 4, no constructor is reached at all. The count therefore proves how far each line progressed. Questions on the exam often hide such facts in a counter.
Pass 3: objects (objectives 4.1 to 4.6)
Perishable("milk", 7, 0.9, 5) calls Perishable.__init__, which calls super().__init__(name, qty, price). The parent sets name, qty and _Item__price, increments the class attribute Item.count through the class name (so there is one shared counter, not one per instance), and returns. The child then sets days.
The attribute written as self.__price inside the class Item is stored under the mangled name _Item__price. That is why hasattr(items[0], "_Item__price") is True and the dictionary of items[1] shows '_Item__price': 0.9. Name mangling is not a security feature; it only avoids accidental name clashes in subclasses.
value is a property: it is read like an attribute (item.value, not item.value()), and it computes qty * price each time. The report shows 18.0 for the first item (12 × 1.5) and 6.3 for milk (7 × 0.9; with floating point the printed value happens to be 6.3).
The method label is overridden in Perishable, which calls the parent's version with super().label() and appends the shelf life. str(items[1]) calls __str__, which is inherited from Item and calls self.label(). Because self is a Perishable, Python finds the overriding label first, and the result is milk x7 (5d). This is polymorphism: __str__ is written once and uses the version of label that belongs to the actual object.
isinstance(items[1], models.Item) is True, because a Perishable is an Item. hasattr(items[0], "days") is False: the first object is a plain Item.
Pass 4: strings and files (objectives 3.1 to 3.3, 5.4 and 5.5)
text.strip().split(",") removes the trailing newline and then splits at commas. Without strip(), the last field of a line such as milk,7,0.9,5\n would be "5\n"; int("5\n") would still work (whitespace is tolerated), but the text of the error message would contain the newline. The f-string in ParseError uses {text!r}, which calls repr() and shows quotes around the text.
The file was written in text mode with encoding="utf-8". The character é takes two bytes, so the first line café,12,1.5 has 11 characters and 12 bytes. The report is deliberately written in binary: "...".encode("utf-8") converts the string to bytes, and write returns the number of bytes. The report text café:18.00\nmilk:6.30 has 20 characters; because of é it has 21 bytes, and the program prints 21. The final read in "rb" mode shows the raw bytes b'caf\xc3\xa9:18.00\nmilk:6.30'.
Pass 5: functional features (objectives 5.1 to 5.3)
make_filter(10) returns the inner function keep, a closure that remembers minimum = 10. Calling keep(item) compares item.value with 10: 18.0 >= 10 is true and 6.3 >= 10 is false. The list comprehension [i.name for i in items if keep(i)] therefore gives ['café'].
sorted(items, key=lambda i: -i.value) uses a lambda that returns the negative value, so higher values come first: ['café', 'milk']. The sort is stable and returns a new list; items itself is unchanged. The dictionary comprehension in summarize builds {'café': 18.0, 'milk': 6.3}.
For the import sequence, revisit Python module lifecycle and entry points. For the text/binary boundary, use Python streams, modes and text files.
Worked example: change the code and predict the result
Statement. A developer changes main.py in two ways. First, the except ParseError clause is removed, leaving only except InventoryError. Second, print(len(errors)) is added after the loop. What happens, and what is printed?
Step 1: which clause catches? Line 3 raises ParseError. The first remaining clause, except InventoryError, matches because ParseError is a subclass. The block executes print("other").
Step 2: what about the list errors? The deleted clause was the only code that appended to errors. It stays empty.
Step 3: the final output. The output contains other twice (lines 3 and 4) and 0 for len(errors). The loop continues, because the exception is handled and the for statement is outside the try.
Why other answers are wrong. An unhandled ParseError would stop the program only if no clause matched, but a parent class does match. A result of 2 for the length would assume that the list is filled somewhere else. A NameError for ParseError does not occur, because the name is still imported even though it is no longer used.
Comparison: where each skill area hides in one sample
| Observation in the code | Area | What to ask yourself |
|---|---|---|
from .errors import ... |
Modules and Packages | Is this a relative import inside a package? |
__name__ == "__main__" |
Modules and Packages | Is the file run or imported? |
except A: ... except B: |
Exceptions | Is the order correct for the hierarchy? |
raise ... from ... |
Exceptions | What is stored in __cause__? |
.split(","), .strip(), f-string |
Strings | What exactly remains, characters or bytes? |
self.__x, super(), class attribute |
OOP | Where is the attribute stored, and who owns it? |
lambda, inner def, [... if ...] |
Functional | When is the captured value read? |
open(..., "wb"), .write() |
I/O | Does the count measure characters or bytes? |
Common pitfalls and exam tips
| Pitfall | What happens | Remedy |
|---|---|---|
| Believing an import line runs again each time | Ordinary imports reuse sys.modules after a successful import; explicit reloads are a separate operation |
Track what was already loaded |
| Putting a parent exception before the child | The child clause is unreachable | Order clauses from specific to general |
Treating self.__x as a private attribute you cannot find |
It is stored as _Class__x |
Look for the mangled name |
Changing Item.count through an instance |
A new instance attribute is created instead | Use the class name to change a shared counter |
| Counting characters when the file is encoded | The byte count is larger for non-ASCII text | Convert with .encode() to count bytes |
Mixing readline() with a for loop |
The loop continues from the current position | Update the file position in your trace |
Wide try blocks |
Unrelated errors are hidden | Wrap only the risky statements |
Exam tip. When a program fails to print the expected text, look for a counter or a side effect that tells you which statements really executed.
Exam tip. In a question with a class hierarchy, write the method resolution order on paper: the instance class first, then its parents.
Exam tip. If an option uses a name that was imported with from module import name, check whether the module name itself is bound; usually it is not.
End-of-lesson case study
Situation. The shop adds a new function to report.py:
def to_lines(items, encoding="utf-8"):
return [f"{i.name}:{i.value:.2f}\n".encode(encoding) for i in items]and the owner writes the result with:
with open("report.txt", "w", encoding="utf-8") as r:
r.writelines(to_lines(items))The program crashes. Identify the error, name the exception, and propose two corrections.
Solution, commented. to_lines returns a list of bytes objects. The file was opened in text mode, and writelines expects strings, so the first call fails with TypeError (the message says that write() argument must be str, not bytes). The exception is not an OSError and not a ValueError, so an except OSError around the block would not help.
Correction 1: open the file in binary mode, open("report.txt", "wb"), and drop the encoding argument, which is not allowed in binary mode. Correction 2: keep text mode and return strings from the function (without .encode). The first correction is better if the report must control the exact bytes, for example when another program reads it; the second is simpler for a human-readable text report. In both cases the with statement closes the file even if the error occurs.
Key terms
- Regular package: a package with an
__init__.pyfile; namespace packages are a separate kind that can omit this file. - Relative import: an import written with a leading dot, resolved from the current package.
sys.modules: the dictionary of modules already imported; imports look here first.- Exception hierarchy: the tree of exception classes that decides which
exceptclause matches. - Name mangling: the renaming of
__xinside a class to_Class__x. - Property: a method that is read like an attribute.
- Closure: an inner function that keeps the variables of its enclosing function.
- Trace: the step-by-step reading of a program with a table of state.
Summary checklist
- I can predict what an import prints and which names it binds.
- I can explain
__name__,__all__and a relative import in a package. - I order
exceptclauses from specific to general. - I can find mangled attributes, class attributes and overridden methods.
- I distinguish characters from bytes when a file is encoded.
- I can read a closure, a lambda and a comprehension in the same pipeline.
- I trace a program in five passes: imports, definitions, calls, state, exceptions.
Official sources
- Python Institute, PCAP-31-03 exam syllabus: https://pythoninstitute.org/pcap-31-03-exam-syllabus (opens in a new tab)
- Python documentation, modules and packages: https://docs.python.org/3.14/tutorial/modules.html (opens in a new tab)
- Python documentation, errors and exceptions: https://docs.python.org/3.14/tutorial/errors.html (opens in a new tab)
- Python documentation, classes: https://docs.python.org/3.14/tutorial/classes.html (opens in a new tab)
- Python documentation, reading and writing files: https://docs.python.org/3.14/tutorial/inputoutput.html#reading-and-writing-files (opens in a new tab)
