Reusing code across files
October 9, 2026
Lecture 6 took our programs outside themselves: files, JSON, the command line. Along the way we wrote import json, import argparse and import os, with only “this brings in some extra tools” as explanation. Today we see what that line really does — and we take Lecture 5’s functions, written once and used many times inside one file, across files:
import;A module is nothing more than a .py file. If you can write a script, you can already write a module.
Take three functions from Lecture 5, slightly shortened, and save them as caesar.py:
# caesar.py
"""The Caesar cipher from Lecture 5."""
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def shift_letter(letter, n):
"""Return letter moved n places along the alphabet; leave non-letters alone."""
if letter not in ALPHABET:
return letter
return ALPHABET[(ALPHABET.index(letter) + n) % 26] # index(): position()
def encrypt(message, n):
"""Return message with every letter shifted n places along the alphabet."""
result = ""
for ch in message.lower():
result = result + shift_letter(ch, n)
return result
def decrypt(message, n):
"""Undo encrypt: shift every letter n places back."""
return encrypt(message, -n)In another file in the same folder:
phhw ph dw qrrq!
meet me at noon!
abcde
import caesar — no .py, no quotes — finds caesar.py and makes everything defined in it reachable as caesar.something. Functions, but variables too: caesar.ALPHABET is a box that lives inside the module.
import is not a declaration: it is an instruction, and the machine carries it out like any other. To watch it happen, a module with a print at the top and one at the bottom:
importPredict the output — how many times do the two talkative lines appear?
main: before
talkative: running my first line
talkative: running my last line
main: between
hello, Ada
The first import runs the whole file, top to bottom, once — the prints included. The second finds the module already loaded and does nothing. Every name the file created is kept in a box of its own, the module, reached with a dot.
Each module has its own global names. Two modules can both have an ALPHABET without ever meeting:
αβγδε
abcde
bcd
The lookup rule of Lecture 2 — local, then global, then built-ins — where “global” means the file the function was written in. encrypt was written in caesar.py, so it sees caesar’s ALPHABET, whatever yours holds.
A string written as the first line of a file or of a function is its docstring: the documentation Python keeps with it. help prints it:
Help on function encrypt in module caesar:
encrypt(message, n)
Return message with every letter shifted n places along the alphabet.
dir lists every name a module offers:
['ALPHABET', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'decrypt', 'encrypt', 'shift_letter']
The names wrapped in __ are mostly Python’s own bookkeeping — we meet one, __name__, shortly. The rest is what the module offers. help(...) and dir(...) work on every module — yours, and the ones that come with Python.
djbp
ciao
import m keeps the prefix: longer to type, but every line says where the name comes from. from m import name drops it: shorter, but the name now sits among your own. When in doubt, keep the prefix.
import *from m import * copies every name of the module into your file. Predict what is printed:
2.718281828459045
math has a name e too — Euler’s number, 2.718…, the base of natural logarithms — and import * silently put it in your box. No error, wrong value: a logic error, the sneaky kind from Lecture 1. With import math it would have stayed math.e.
While writing a module you test it at the bottom — and forget the test there:
Now another program only wants the function:
testing: hello, test
hello, Ada
import runs the whole file, so every program that imports greetings prints the test line first. The same file has two jobs: a script you run, and a module others import. It needs a way to tell which job it is doing.
if __name__ == "__main__":Every module has a box called __name__. Python fills it before the first line runs: "__main__" if the file was run, its own name if it was imported.
On import caesar, the machine looks for caesar.py, in order:
First match wins — like the scope lookup. Nothing found:
ModuleNotFoundError: No module named 'caesr'
random.pyYou are practising with the random module, so you call your file random.py. Then, in the same folder, a second program:
(intro2python) $ python dice.py
AttributeError: partially initialized module 'random' has no attribute 'randint' (most likely due to a circular import)
Step 1 of the search finds your random.py before Python’s, and it has no randint. The message blames a “circular import” and never says that your file is hiding Python’s, which is why this one costs an afternoon. Never name a file after a module you use: no random.py, json.py, string.py, csv.py, datetime.py.
Python comes with a few hundred modules. You already used four: keyword in Lecture 3, and three in Lecture 6. A short tour of the ones this course reaches for:
| Module | For | Seen in |
|---|---|---|
json, argparse, os |
files, command line, folders | Lecture 6 |
math |
square roots, π, rounding | today |
random |
dice, shuffling, sampling | today |
collections |
Counter: counting things |
today, Lectures 8 and 10 |
string |
ready-made sets of characters | today |
datetime |
dates and differences between them | today, Lecture 8 |
csv |
spreadsheet-style files | the practicals |
re |
regular expressions | Lecture 9 |
The full list, with documentation: docs.python.org/3/library.
math1.4142135623730951
3.141592653589793
2 3
Compare int(2.7) from Lecture 3: it just drops the fraction. math.floor always goes down — they differ on negative numbers, int(-2.7) is -2 and math.floor(-2.7) is -3.
random4
rock
['A', 'K', 'Q', 'J']
[54, 26, 74, 78, 27, 52]
randint(1, 6) includes the 6 — unlike range(1, 6). And shuffle changes the list and returns None, like sort in Lecture 3.
The numbers come from a calculation that starts from a seed. Fix the seed and the “random” sequence is the same every time:
16 41
16 41
A seed makes a random program repeatable — which is what you need when you are looking for a bug in it, or when someone else must get your exact results.
collections.CounterIn Lecture 5 you wrote word_frequency by hand. It already exists:
Counter({'the': 3, 'sat': 2, 'cat': 1, 'on': 1, 'mat': 1, 'and': 1, 'dog': 1, 'too': 1})
3 1 0
[('the', 3), ('sat', 2)]
A Counter is a dictionary that counts. A word it has never seen counts 0 — no KeyError, no .get(w, 0). most_common(n) gives the top n as (item, count) pairs, the sorting done for you.
stringReady-made strings of characters, so that you do not type them by hand:
abcdefghijklmnopqrstuvwxyz
0123456789
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
“conversations?”
conversations
string.punctuation holds only the punctuation of ASCII, the 128-character table of Lecture 1. The curly quotes of a real book are not in it, so the first strip stops at the ” and removes nothing at all.
datetime6496 days from Python 0.9 to Python 3.0
Wednesday 03 December 2008
.days turns the difference into a whole number. date.today() gives the real current date. strftime turns a date into text, following a pattern: %d day, %B month name, %Y year, %A weekday.
Thousands more modules — packages — are written by other people and installed with one command, in the terminal, with your environment active:
(intro2python) $ pip install beautifulsoup4
Then, in Python, it imports like any other module:
bs4 4.15.0
Installing is per environment. No (intro2python) in front of the prompt, and it goes into another Python — the one VS Code is not using. Then import fails with ModuleNotFoundError, although “it is installed”. Check the prompt, and the interpreter in VS Code’s status bar (Lecture 1).
| Package | For |
|---|---|
numpy |
fast arrays of numbers |
pandas |
tables, as in a spreadsheet |
matplotlib |
plots |
requests, beautifulsoup4 |
downloading and reading web pages |
nltk, spacy |
language: tokens, tags, parsing |
None of them is needed for the exam. All of them are used exactly the way we used caesar today: install once, import, then the names behind the dot.
.py file; import runs it once and gives you its names behind a dot.import m keeps the prefix; from m import name drops it; avoid import *.if __name__ == "__main__": — code that runs only when the file is the program.pip install, in the right environment.Predict the screen for the program below — and then for python shop.py.
shop loaded
6
The program prints shop loaded once, then 6. The second import does nothing; our PRICE is not the module’s, so total still multiplies by 3; and testing: never appears, because __name__ is "shop".
Run as a script instead, the guard lets the test through:
(intro2python) $ python shop.py
shop loaded
testing: 6
For each line, write the import that makes it work. One click per answer.
The call tells you the import: a prefix means the module was imported, no prefix means the name was.
Someone left you a message in resources/secret_message.txt, encrypted with a Caesar cipher. Nobody told you the key.
nvcc ufev! kyv jvtivk gyirjv zj: r dfulcv zj aljk r wzcv.
caesar.py, each with a one-line docstring. Under if __name__ == "__main__":, check that decrypt(encrypt(t, n), n) gives back t for a few texts and keys.main.py, read the message from the file (Lecture 6), import your module, and use crack on it. What is the key? What is the phrase?Stretch: add best_key(message) to caesar.py, which finds the key without your eyes: for each key, count how many words of the decrypted text are common English words — the, a, is, of, and, to, in, it — and return the key with the highest count.
The five functions as in Lecture 5, each with its docstring; then, at the bottom of caesar.py:
(intro2python) $ python caesar.py
tests done
.strip() removes the \n at the end of the line (Lecture 6). The test runs only when caesar.py is the program: imported by main.py, it stays quiet.
(intro2python) $ python main.py
0 nvcc ufev! kyv jvtivk gyirjv zj: r dfulcv zj aljk r wzcv.
1 mubb tedu! jxu iushuj fxhqiu yi: q cetkbu yi zkij q vybu.
2 ltaa sdct! iwt htrgti ewgpht xh: p bdsjat xh yjhi p uxat.
3 kszz rcbs! hvs gsqfsh dvfogs wg: o acrizs wg xigh o twzs.
4 jryy qbar! gur frperg cuenfr vf: n zbqhyr vf whfg n svyr.
5 iqxx pazq! ftq eqodqf btdmeq ue: m yapgxq ue vgef m ruxq.
6 hpww ozyp! esp dpncpe ascldp td: l xzofwp td ufde l qtwp.
7 govv nyxo! dro combod zrbkco sc: k wynevo sc tecd k psvo.
8 fnuu mxwn! cqn bnlanc yqajbn rb: j vxmdun rb sdbc j orun.
9 emtt lwvm! bpm amkzmb xpziam qa: i uwlctm qa rcab i nqtm.
10 dlss kvul! aol zljyla woyhzl pz: h tvkbsl pz qbza h mpsl.
11 ckrr jutk! znk ykixkz vnxgyk oy: g sujark oy payz g lork.
12 bjqq itsj! ymj xjhwjy umwfxj nx: f rtizqj nx ozxy f knqj.
13 aipp hsri! xli wigvix tlvewi mw: e qshypi mw nywx e jmpi.
14 zhoo grqh! wkh vhfuhw skudvh lv: d prgxoh lv mxvw d iloh.
15 ygnn fqpg! vjg ugetgv rjtcug ku: c oqfwng ku lwuv c hkng.
16 xfmm epof! uif tfdsfu qisbtf jt: b npevmf jt kvtu b gjmf.
17 well done! the secret phrase is: a module is just a file.
18 vdkk cnmd! sgd rdbqds ogqzrd hr: z lnctkd hr itrs z ehkd.
19 ucjj bmlc! rfc qcapcr nfpyqc gq: y kmbsjc gq hsqr y dgjc.
20 tbii alkb! qeb pbzobq meoxpb fp: x jlarib fp grpq x cfib.
21 sahh zkja! pda oaynap ldnwoa eo: w ikzqha eo fqop w beha.
22 rzgg yjiz! ocz nzxmzo kcmvnz dn: v hjypgz dn epno v adgz.
23 qyff xihy! nby mywlyn jblumy cm: u gixofy cm domn u zcfy.
24 pxee whgx! max lxvkxm iaktlx bl: t fhwnex bl cnlm t ybex.
25 owdd vgfw! lzw kwujwl hzjskw ak: s egvmdw ak bmkl s xadw.
# caesar.py, the new function
def best_key(message):
"""Return the key whose decryption contains the most common words."""
best = 0
best_count = -1
for n in range(26):
count = 0
for word in decrypt(message, n).split():
if word.strip(".,;:!?") in COMMON:
count += 1
if count > best_count:
best = n
best_count = count
return best(intro2python) $ python main_auto.py
key: 17
well done! the secret phrase is: a module is just a file.
The program does what your eyes did: the right key is the one that turns the text into real words. strip(".,;:!?") takes the punctuation off, so is: counts as is.
Make texttools.py with:
read_book(path) — Lecture 6’s function: the lines of a Gutenberg book;clean_words(lines) — every word, lower-cased, punctuation stripped from both ends with string.punctuation plus the curly quotes, empty ones dropped;top_words(words, n) — the n most common words, with Counter.Then in main.py: the 10 most common words of resources/alice.txt.
# texttools.py
"""Small helpers for reading and counting the words of a book."""
import string
from collections import Counter
STRIP = string.punctuation + "“”‘’—"
def read_book(path):
"""Return the lines of a Gutenberg book, without the licence."""
body = []
inside = False
with open(path, "r", encoding="utf-8") as f:
for line in f:
if line.startswith("*** END OF"):
break
if inside:
body.append(line.strip())
if line.startswith("*** START OF"):
inside = True
return body# texttools.py, continued
def clean_words(lines):
"""Return the words of lines, lower-cased, without outer punctuation."""
words = []
for line in lines:
for w in line.split():
w = w.lower().strip(STRIP)
if w != "":
words.append(w)
return words
def top_words(words, n):
"""Return the n most common words as (word, count) pairs."""
return Counter(words).most_common(n)(intro2python) $ python main.py
the 4
of 3
or 3
alice 2
was 2
to 2
her 2
sister 2
and 2
had 2
main.py reads like a description of the task. And the module imports its own modules: main.py never needed to know about string or Counter.
Counter. Print the sums in order, 2 to 12, each with a bar of *, one star for every 10 rolls.A Counter starts every count at 0, so sums[total] += 1 works even for a sum it has never seen.
one roll: 10
2 **
3 *****
4 *******
5 ***********
6 **************
7 ****************
8 *************
9 ***********
10 *******
11 *******
12 **
7: six ways to make it (1+6, 2+5, … 6+1), only one way to make 2 or 12.
Write days.py, which takes a date on the command line as three numbers and prints how many days ago it was, and which weekday it fell on. A date in the future should say “in … days” instead:
(intro2python) $ python days.py 2000 1 1
That was a Saturday, 9814 days ago.
(intro2python) $ python days.py 2030 1 1
That will be a Tuesday, in 1144 days.
(The numbers depend on the day you run it.)
# days.py
import argparse
from datetime import date
parser = argparse.ArgumentParser()
parser.add_argument("year", type=int)
parser.add_argument("month", type=int)
parser.add_argument("day", type=int)
args = parser.parse_args()
then = date(args.year, args.month, args.day)
gap = (date.today() - then).days
weekday = then.strftime("%A")
if gap >= 0:
print(f"That was a {weekday}, {gap} days ago.")
else:
print(f"That will be a {weekday}, in {-gap} days.")type=int from Lecture 6 does the conversions. A date that does not exist, like 2026 2 30, stops date(...) with a ValueError — the try / except of Lecture 6 would turn it into a polite message.
Write grammar.py with lists of determiners, adjectives, nouns and verbs, and a function sentence() that returns a random sentence of the shape Det Adj Noun Verb Det Noun:
the green linguist reads a sandwich
every tired cat ignores the theory
From main.py, print five of them. Stretch: an optional seed argument, sentence(seed=None), that makes the output repeatable.
# grammar.py
"""Random sentences of the shape Det Adj Noun Verb Det Noun."""
import random
DETERMINERS = ["the", "a", "every", "no"]
ADJECTIVES = ["green", "tired", "curious", "silent"]
NOUNS = ["cat", "linguist", "theory", "sandwich"]
VERBS = ["reads", "ignores", "admires", "eats"]
def sentence(seed=None):
"""Return a random sentence: Det Adj Noun Verb Det Noun."""
if seed is not None:
random.seed(seed)
words = [random.choice(DETERMINERS), random.choice(ADJECTIVES),
random.choice(NOUNS), random.choice(VERBS),
random.choice(DETERMINERS), random.choice(NOUNS)]
return " ".join(words)(intro2python) $ python main.py
every curious theory reads the theory
the silent theory eats no cat
no curious sandwich ignores no cat
every tired cat ignores no linguist
no curious theory eats every theory
True
Grammatical, and mostly nonsense — Chomsky’s colourless green ideas in four lists. random.seed resets the generator of the whole program, so every call after sentence(seed=7) is repeatable too. The lists are in capitals because nobody should change them: the convention from Lecture 3.
Intro to Programming (Python) · Fall 2026