Modules and the standard library

INPUT · Slides

One file keeps growing

01 / 06

Everything has lived in one file

Every program so far has been finished off inside a single file. While it is short, that is far and away the easiest way.

Real programs do not fit in one file, though. Ten functions, three classes, setting the data up, checking it, showing it — it all piles on. At a few thousand lines, even the person who wrote the file cannot find the bit they want.

02 / 06

A look at the everything file

Below, "the price data", "working out the total" and "showing it on screen" are all living together. It is only about ten lines and three roles are already mixed in. Can you pick them out?

While it is short, mixed together still reads. The trouble starts after this.

prices = [120, 80, 250]total = 0for price in prices:    total += pricefor price in prices:    print(f"- ${price}")print(f"total ${total}")

Result

- $120
- $80
- $250
total $450

03 / 06

The trouble comes when you change it, not when you write it

A big file starts to hurt when you come back to it later.

  • to find the place you want to change, you read past code that has nothing to do with it
  • you give something a similar name and overwrite an earlier variable without meaning to
  • a piece of work you would like in another program can only be copied wholesale

Even the person who wrote it has forgotten a week on. The bigger the file, the longer remembering takes.

04 / 06

Cut by role, not by line count

So where do you cut? Not "cut once it passes a hundred lines" — cut by role. The example above falls into three.

  • data … the prices themselves
  • working out … producing the total
  • showing … putting it on screen

Start by splitting it into functions. Once the name tells you what is inside, you have split it far enough.

def total_up(prices):    answer = 0    for price in prices:        answer += price    return answerdef show(prices):    for price in prices:        print(f"- ${price}")prices = [120, 80, 250]show(prices)print(f"total ${total_up(prices)}")

Result

- $120
- $80
- $250
total $450

05 / 06

A copy means fixing two places

Working out a total serves the shopping and the test scores alike. Write it into one file, though, and copying is the only way to use it in another program.

Copying is easy, but when a mistake turns up you have to fix both. Fixing one and letting the other drift is the hardest kind of bug there is to find.

"Keep it in one place and call it from anywhere" makes the whole worry disappear.

06 / 06

Two tabs from here on

From these exercises on, two file tabs sit above the editor. Tap to switch between them.

The one that starts running when you press the run button is always main.py. The other is a place to move things into next lesson. Leave it empty for now.

First, practise splitting main.py into a function per role. Once the split is done, dividing the files takes no time at all.