Lite / Textbooks / Engineering Programming With Python / Chapter 5
5. Modules, objects and data structures
Introduction
Past a hundred lines, one script becomes a tangle. Modules split a program into files with clear jobs; classes bundle data with the methods that guard it, so a sensor object can keep its own readings and refuse impossible ones. Then pick the right container: a list keeps order, a set answers membership, a dictionary looks up by key, a stack undoes, and a queue serves in arrival order.
Figure 5.1. Same items in, different order out (described in words)
Items A, B and C are pushed in that order. A stack gives them back as C, B, A (last in, first out); a queue gives them back as A, B, C (first in, first out).
Explanation
Built from 4 School lessons. Each part is the lesson's own explanation.
5.1 One script is not a system
A rover planner works perfectly as one 600-line file. Then you change a unit conversion and three unrelated features break. Why?
A module is just a .py file
Any file units.py is a module called units. Another file in the same folder can write import units and call units.cm_to_m(250), or from units import cm_to_m to use the name directly. Python searches the folder of the script you ran first, then the standard library and installed packages.
Interfaces, not internals
Each module should expose a few functions or classes (its interface) and keep its helpers private. By convention, a name starting with an underscore, such as _clamp, is internal. Other modules use only the interface, so you can rewrite the inside freely as long as the interface and its tests still hold.
Arrows only go one way
Draw an arrow from each module to the modules it imports. Good packages form layers: small utility modules at the bottom, the program's entry point at the top, and no loops. A circular import (A imports B and B imports A) means neither can be loaded or tested on its own; fix it by moving the shared code down a layer or the calling code up.
Common mix-ups
Splitting code into files makes it slower.
✓ Imports happen once and are cached; the cost is negligible. The benefit is code you can understand, test and change in pieces.If it runs, the structure doesn't matter.
✓ Structure decides how much breaks when you change something. One-way dependencies keep that blast radius small.
Open the Lite lesson: One script is not a system
5.2 One blueprint, many sensors
A robot has six identical range sensors, each with its own offset and its own readings. Do you write six sets of variables, or one blueprint?
Class, instance, self
class RangeSensor: defines a new type. front = RangeSensor("front", 2) calls __init__ to build one instance. Inside each method, self is the particular object the method was called on, so self.readings means this sensor's readings.
Attributes live on the object
Assigning self.offset_cm = offset_cm stores a value on that one object; vars(front) shows them. Python looks up an attribute on the object first, then on its class. Constants that every instance shares, like unit = "cm", can sit on the class.
The shared-list trap
A list (or dict) written in the class body exists once, for every instance. Appending through self.readings changes that one shared list, so every sensor sees every reading. Create mutable state inside __init__ so each object gets its own.
Common mix-ups
self is a keyword that means the class.
✓ self is just the conventional name for the first parameter, which receives the instance the method was called on.Each object gets its own copy of every class attribute.
✓ Class attributes are shared. Only attributes assigned on self belong to one object.
Open the Lite lesson: One blueprint, many sensors
5.3 List, tuple, set or dict? Pick the right container
Checking whether a part number is in a list of 100,000 parts takes up to 100,000 comparisons. With a set it takes about one. What changed?
Four containers, four questions
list: ordered, indexable, may repeat; 'what is the 5th reading?'. tuple: like a list but fixed, perfect for a record such as (row, col). set: unordered, no repeats; 'is this in the collection?'. dict: keys mapped to values; 'what is the stock of this part?'.
Why sets and dicts are fast
A set or dict computes a hash of the key, which says roughly where to look, so x in s and d[k] take about the same time whether there are 10 items or 10 million (on average). x in some_list compares items one by one: up to n comparisons.
Keys must not change
Only immutable values can be set members or dict keys: numbers, strings and tuples of them. That is another reason to store a cell as the tuple (3, 7) rather than the list [3, 7]. Lists can't be hashed, so {[3, 7]} raises TypeError.
Common mix-ups
Sets are just lists without duplicates.
✓ Sets are hash tables: unordered, with fast membership tests. That speed is the main reason to use one.Dicts are slow because they are complicated.
✓ Average dict lookup is about as fast as list indexing and far faster than searching a list.
Open the Lite lesson: List, tuple, set or dict? Pick the right container
5.4 Stacks and queues: who goes next?
A robot cell gets jobs faster than it can do them. Do you serve the newest job first, or the oldest? The answer changes everything.
Stack: last in, first out
A Python list is a stack: s.append(x) pushes onto the top, s.pop() removes and returns the top. Both are fast (O(1)). Use it for undo, for backtracking, and for depth-first search.
Queue: first in, first out
from collections import deque gives a double-ended queue. q.append(x) joins the back; q.popleft() serves the front, both in O(1). Don't use list.pop(0) for a queue: it shifts every remaining item, which is O(n).
Empty means stop
Popping from an empty list or deque raises IndexError. Loops usually run while q: (an empty container is falsy), so they end naturally when the work is done.
Common mix-ups
A list works fine as a queue.
✓ It works, but list.pop(0) is O(n). deque gives O(1) at both ends.Stacks and queues are different kinds of storage.
✓ They are the same items with different rules about which one leaves next.
Open the Lite lesson: Stacks and queues: who goes next?
Worked examples
One script is not a system: example 1
Split this conversion out of a planner script into its own module, then use it.
Solution
# file: units.py
"""Unit conversions shared by the rover planner."""
CM_PER_M = 100
def cm_to_m(cm):
"""Convert a length in centimetres to metres."""
return cm / CM_PER_Mfrom units import cm_to_m
print(cm_to_m(250)) # 2.5The second file only knows the name cm_to_m and its promise. If you later change how the conversion is done, nothing else needs to change.
One blueprint, many sensors: example 1
Model a range sensor with a calibration offset, record readings and report their mean.
Solution
class RangeSensor:
unit = "cm" # shared by every sensor
def __init__(self, name, offset_cm):
self.name = name
self.offset_cm = offset_cm
self.readings = [] # one list per sensor
def record(self, raw_cm):
self.readings.append(raw_cm + self.offset_cm)
def mean(self):
if not self.readings:
raise ValueError(f"{self.name} has no readings yet")
return sum(self.readings) / len(self.readings)
front = RangeSensor("front", 2)
rear = RangeSensor("rear", -1)
front.record(50)
front.record(54)
rear.record(80)
print(front.mean(), rear.mean()) # 54.0 79.0
print(vars(rear)) # {'name': 'rear', 'offset_cm': -1, 'readings': [79]}List, tuple, set or dict? Pick the right container: example 1
Store visited cells and per-cell costs for a planner.
Solution
visited = set()
cost = {}
start = (3, 0)
visited.add(start)
cost[start] = 0
for cell, c in [((3, 1), 1), ((2, 0), 1), ((3, 1), 1)]:
if cell not in visited: # average O(1), however big visited gets
visited.add(cell)
cost[cell] = c
print(len(visited), cost[(2, 0)], (9, 9) in visited) # 3 1 False
print(cost.get((9, 9), "unreached")) # unreachedStacks and queues: who goes next?: example 1
Process jobs in arrival order and keep an undo history.
Solution
from collections import deque
jobs = deque()
for job in ["drill A", "drill B", "inspect A"]:
jobs.append(job)
print(jobs.popleft()) # drill A (oldest first)
jobs.append("drill C")
print(list(jobs)) # ['drill B', 'inspect A', 'drill C']
undo = []
undo.append("move wp3")
undo.append("delete wp5")
print(undo.pop()) # delete wp5 (newest first)
while jobs: # stops when the queue is empty
print("doing", jobs.popleft())Interactive figures, in words
Figure 5.2 from One script is not a system
Select units.py, then grid.py, then main.py and count the orange modules each time. Which module is safest to change, and which is riskiest? Now tick the shortcut that lets grid.py import planner.py and read the warning.
The dependency explorer shows seven modules in layers: units.py at the bottom; grid.py and report.py import units; io_csv.py and planner.py import grid; main.py imports io_csv, planner and report; test_planner.py imports planner and grid. Changing units.py affects all five modules above it. Ticking the shortcut makes grid.py also import planner.py, creating a circular import.
Figure 5.3 from One blueprint, many sensors
Record a few readings on front and rear, then compare vars(front) and vars(rear). Call rear.mean() before it has readings and read the error. Now tick the bug toggle and record on front only: what happened to rear?
The inspector shows a RangeSensor class with a front sensor (offset 2 cm) and a rear sensor (offset −1 cm). Recording 50 cm on the front stores 52 in front's own list only. With the bug toggle on, readings live on the class, so the same 52 appears in both sensors' readings.
Figure 5.4 from List, tuple, set or dict? Pick the right container
Open Dict (inventory) mode and look up each part. Note how many names a list scan would have to compare. Look up the part that isn't stocked: what happens with [] and with .get()? Then switch to List mode and compare.
The dict mode shows an inventory of six parts. Looking up 'servo SG90' returns 6 directly; as a list of pairs a scan would compare 4 names. Looking up an unstocked 'M4 bolt' raises KeyError with square brackets but returns 0 with .get(key, 0); a list scan would check all 6 names.
Laboratory
These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.
- Code Lab (Studio)
Write a Sensor class that stores readings and returns their mean, and test that two sensors do not share data.
Open on the full site - Nexus: Smart Transportation Junction (Nexus project)
Model the cars waiting at a light as a queue and count how many clear in one green phase.
Open on the full site
Practice
Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.
- units.py defines cm_to_m. Which line lets another file call cm_to_m(250) with no prefix?
Answer it in “One script is not a system” - grid.py imports planner.py so GridMap can call bfs, and planner.py imports grid.py. What is the best fix?
Answer it in “One script is not a system” - Inside record(self, raw_cm), what is self when you call rear.record(80)?
Answer it in “One blueprint, many sensors” - Which class definition gives each sensor its own readings list?
Answer it in “One blueprint, many sensors” - You need the stock quantity for any part number, looked up thousands of times. Which container?
Answer it in “List, tuple, set or dict? Pick the right container” - stock = {'M3-BOLT': 120}. What does stock.get('M4-BOLT', 0) return?
Answer it in “List, tuple, set or dict? Pick the right container” - A robot cell queues jobs in arrival order: from collections import deque; q = deque(); q.append(27); q.append(49); q.popleft(); q.append(37); q.popleft(). What value does the final q.popleft() return?
Answer it in “Stacks and queues: who goes next?” - An editor's undo button should reverse the most recent change first. Which structure?
Answer it in “Stacks and queues: who goes next?”
Engineering applications
Undo
Every editor's undo button is a stack: each action is pushed, and undo pops the most recent. Print queues, message buffers and robot task lists are queues, served strictly in the order they arrived.
Fleets of sensors
A greenhouse with twenty sensors becomes twenty objects of one class, each with its own calibration and readings. A dictionary keyed by sensor name finds any one of them instantly.
Watch (optional)
Streaming video uses a lot of data. Everything you need is in the text.
- “Python OOP Tutorial 1: Classes and Instances” by Corey Schafer
- “Data Structures: Stacks and Queues” by HackerRank
- “Data Structures: Crash Course Computer Science #14” by CrashCourse
Summary
- Modules split a program by job; import what you need and keep top-level code minimal.
- A class is a blueprint; each instance keeps its own data, reached through self.
- Choose containers by the question you ask most: order, membership or lookup by key.
- A stack is last in, first out; a queue is first in, first out.
Glossary
- Classes and objects
- A class is a blueprint that bundles data (attributes) and behaviour (methods). Each object made from it has its own copy of the data; self refers to that object inside a method. Field Guide
- Dictionaries
- A dictionary maps keys to values, as in {"red": 2, "green": 5}, and looks values up by key in roughly constant time. Field Guide
- Lists and indexing
- A list is an ordered, changeable collection written in square brackets. Items are numbered from 0, and negative indices count back from the end. Field Guide
- Slicing
- A slice seq[start:stop:step] takes items from start up to but not including stop, moving step at a time; any part can be left out. Field Guide
- List comprehensions
- A list comprehension builds a new list from an existing sequence in one expression: [f(x) for x in items if condition]. Field Guide
Project: A stores inventory
Model a workshop's parts store as a small package: a Part class, a dictionary from part number to Part, and a queue of incoming orders. Process the orders, report shortfalls, and keep an undo stack so the last change can be reversed.
Deliverables
- Two modules with a clear split of jobs
- Tests for ordering, shortfall and undo
- A paragraph explaining each container choice
Write it up on paper or in your own notes. Lite never stores what you write.
References
- John V. Guttag (2016). Introduction to Computation and Programming Using Python, 2nd edition. MIT Press.
- Thomas H. Cormen et al. (2009). Introduction to Algorithms, 3rd edition. MIT Press.
- Python Software Foundation. The Python Tutorial. Python Software Foundation. Link
Further reading from the lessons
- Python tutorial: Modules
The official explanation of import, the module search path and packages. - Python tutorial: Classes
The official tour of classes, instances, class and instance variables (including the shared-list trap). - Python docs: data structures
Lists, tuples, sets and dictionaries side by side, with examples. - Python docs: collections.deque
All deque operations and their costs, including maxlen for fixed-size buffers.