Modules

Reusing code across files

Paolo Rota

October 9, 2026

Where we are

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:

  • what a module is, and what the machine does on import;
  • how to turn your own functions into a module and reuse them across files;
  • a tour of the standard library, the modules Python comes with;
  • how to install the ones it does not.

A module is nothing more than a .py file. If you can write a script, you can already write a module.

Your first module

The Caesar cipher, in its own file

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)

Using it from another file

In another file in the same folder:

import caesar

secret = caesar.encrypt("Meet me at noon!", 3)
print(secret)
print(caesar.decrypt(secret, 3))
print(caesar.ALPHABET[:5])
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.

A module that talks

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:

# talkative.py
print("talkative: running my first line")

GREETING = "hello"

def greet(name):
    return GREETING + ", " + name

print("talkative: running my last line")

What the machine does on import

Predict the output — how many times do the two talkative lines appear?

print("main: before")
import talkative
print("main: between")
import talkative
print(talkative.greet("Ada"))
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.

A module is a scope

Each module has its own global names. Two modules can both have an ALPHABET without ever meeting:

ALPHABET = "αβγδε"                  # our own, in this file

print(ALPHABET)                     # ours
print(caesar.ALPHABET[:5])          # the module's
print(caesar.encrypt("abc", 1))     # the module uses ITS alphabet
αβγδε
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.

Notes for humans: docstrings

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(caesar.encrypt)
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:

print(dir(caesar))
['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.

Ways to import

Four spellings

import caesar                       # caesar.encrypt(...)
import caesar as cs                 # cs.encrypt(...)          — a shorter name
from caesar import encrypt          # encrypt(...)             — no prefix
from caesar import encrypt, decrypt # several at once
import caesar as cs
from caesar import decrypt

print(cs.encrypt("ciao", 1))
print(decrypt("djbp", 1))
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.

The one to avoid: import *

from m import * copies every name of the module into your file. Predict what is printed:

e = "my exam grade: 30"

from math import *

print(e)
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.

Script or module?

Test code that runs at the wrong time

While writing a module you test it at the bottom — and forget the test there:

# greetings.py
def greet(name):
    """Return a greeting for name."""
    return "hello, " + name

print("testing:", greet("test"))          # a quick check

Now another program only wants the function:

import greetings

print(greetings.greet("Ada"))
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.

# greet.py
def greet(name):
    """Return a greeting for name."""
    return "hello, " + name

if __name__ == "__main__":                # only when run, not imported
    print("testing:", greet("test"))
import greet

print(greet.__name__)
print(greet.greet("Ada"))
greet
hello, Ada
(intro2python) $ python greet.py
testing: hello, test

Where Python looks

The search order

On import caesar, the machine looks for caesar.py, in order:

  1. the folder of the script being run (in a notebook: the notebook’s folder);
  2. the standard library, the modules that come with Python;
  3. the packages installed into your environment.

First match wins — like the scope lookup. Nothing found:

import caesr
ModuleNotFoundError: No module named 'caesr'

The classic trap: naming your file random.py

You are practising with the random module, so you call your file random.py. Then, in the same folder, a second program:

# random.py
import random
print(random.randint(1, 6))
# dice.py
import random
print(random.randint(1, 6))
(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.

The standard library

Batteries included

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.

math

import math

print(math.sqrt(2))
print(math.pi)
print(math.floor(2.7), math.ceil(2.1))   # round down, round up
1.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.

random

import random

print(random.randint(1, 6))                # a whole number, 1 to 6 INCLUDED
print(random.choice(["rock", "paper", "scissors"]))

cards = ["A", "K", "Q", "J"]
random.shuffle(cards)                      # changes the list in place
print(cards)
print(random.sample(range(1, 91), 6))      # 6 different numbers, no repeats
4
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.

Repeatable randomness

The numbers come from a calculation that starts from a seed. Fix the seed and the “random” sequence is the same every time:

random.seed(2026)                          # the same seed...
print(random.randint(1, 100), random.randint(1, 100))
random.seed(2026)                          # ...gives the same numbers
print(random.randint(1, 100), random.randint(1, 100))
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.Counter

In Lecture 5 you wrote word_frequency by hand. It already exists:

from collections import Counter

words = "the cat sat on the mat and the dog sat too".split()
counts = Counter(words)

print(counts)
print(counts["the"], counts["dog"], counts["unicorn"])
print(counts.most_common(2))
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.

string

Ready-made strings of characters, so that you do not type them by hand:

import string

print(string.ascii_lowercase)        # the Caesar ALPHABET
print(string.digits)
print(string.punctuation)
abcdefghijklmnopqrstuvwxyz
0123456789
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
word = "“conversations?”"
print(word.strip(string.punctuation))
print(word.strip(string.punctuation + "“”‘’—"))
“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.

datetime

from datetime import date

python_0_9 = date(1991, 2, 20)      # first public Python
python_3_0 = date(2008, 12, 3)

gap = python_3_0 - python_0_9       # a difference between dates...
print(gap.days, "days from Python 0.9 to Python 3.0")
print(python_3_0.strftime("%A %d %B %Y"))
6496 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.

Beyond the standard library

Installing a package

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:

import bs4                           # we use it in Lecture 10

print(bs4.__name__, bs4.__version__)     # __version__: the installed version
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).

A few names worth knowing

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.

What to take away

  1. A module is a .py file; import runs it once and gives you its names behind a dot.
  2. Each module is its own scope: its names do not clash with yours.
  3. import m keeps the prefix; from m import name drops it; avoid import *.
  4. if __name__ == "__main__": — code that runs only when the file is the program.
  5. Never name your file like a module you use.
  6. Standard library: already there. Other packages: pip install, in the right environment.

Try it now

Who prints what?

# shop.py
print("shop loaded")

PRICE = 3

def total(n):
    return n * PRICE

if __name__ == "__main__":
    print("testing:", total(2))

Predict the screen for the program below — and then for python shop.py.

import shop
import shop
PRICE = 100
print(shop.total(2))
shop loaded
6

Who prints what? — answer

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

Which import?

For each line, write the import that makes it work. One click per answer.

print(math.sqrt(81))
import math
print(math.sqrt(81))
9.0
print(sqrt(81))
from math import sqrt
print(sqrt(81))
9.0
print(m.sqrt(81))
import math as m
print(m.sqrt(81))
9.0
print(Counter("banana").most_common(1))
from collections import Counter
print(Counter("banana").most_common(1))
[('a', 3)]

The call tells you the import: a prefix means the module was imported, no prefix means the name was.

Exercises

Exercise 1 — The secret message

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.
  1. Put all five Caesar functions of Lecture 5 in 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.
  2. In 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.

Exercise 1 — solution

The five functions as in Lecture 5, each with its docstring; then, at the bottom of caesar.py:

if __name__ == "__main__":
    for text in ["hello", "meet me at noon!", ""]:
        for n in [1, 3, 25]:
            if decrypt(encrypt(text, n), n) != text:
                print("BROKEN:", repr(text), n)
    print("tests done")
(intro2python) $ python caesar.py
tests done
# main.py
import caesar

with open("resources/secret_message.txt", "r", encoding="utf-8") as f:
    secret = f.read().strip()

caesar.crack(secret)

.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.

Exercise 1 — solution, run

(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.

Exercise 1 — stretch solution

# 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.

Exercise 2 — A text-tools module

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.

Exercise 2 — solution (1/2)

# 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

Exercise 2 — solution (2/2)

# 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)

Exercise 2 — solution, run

# main.py
import texttools

lines = texttools.read_book("resources/mini_alice.txt")   # or alice.txt
words = texttools.clean_words(lines)
for word, count in texttools.top_words(words, 10):
    print(f"{word:<8}{count:>6}")
(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.

Exercise 3 — Two dice, a thousand times

  1. Roll two dice and print their sum.
  2. Roll them 1000 times and count how often each sum comes up, with a Counter. Print the sums in order, 2 to 12, each with a bar of *, one star for every 10 rolls.
  3. Which sum is most common? Why that one?

A Counter starts every count at 0, so sums[total] += 1 works even for a sum it has never seen.

Exercise 3 — solution

import random
from collections import Counter

print("one roll:", random.randint(1, 6) + random.randint(1, 6))

random.seed(1)
sums = Counter()
for i in range(1000):
    sums[random.randint(1, 6) + random.randint(1, 6)] += 1

for total in range(2, 13):
    print(f"{total:>2} {'*' * (sums[total] // 10)}")
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.

Exercise 4 — How long ago?

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.)

Exercise 4 — solution

# 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.

Exercise 5 — A sentence machine

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.

Exercise 5 — solution

# 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)

Exercise 5 — solution, run

# main.py
import grammar

for i in range(5):
    print(grammar.sentence())
print(grammar.sentence(seed=7) == grammar.sentence(seed=7))
(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.

Questions?