🗃️ Modules & Structure

Split a program into tidy pieces

← Back to Architecture

📁 One giant file vs. many small ones

As programs grow, one huge file becomes impossible to manage. Modules let you split code into separate files, each focused on one topic — like chapters in a book.

In Python, every .py file is a module. A folder of modules is a package.

📦 Importing modules

You already use modules! Python's standard library is full of them.

import math print(math.sqrt(16)) # 4.0 from random import choice print(choice(["a", "b"])) # picks one

💡 Two import styles

  • import math → use as math.sqrt().
  • from math import sqrt → use as sqrt() directly.

🧩 Separation of concerns

Each module should handle one concern. A typical small app might split like this:

myapp/ ├── data.py # loading & saving ├── logic.py # the rules & calculations ├── display.py # printing to the screen └── main.py # ties it all together

When the display needs to change, you only touch display.py — the logic stays untouched. This is the heart of good architecture.

🔗 Low coupling, high cohesion

  • High cohesion: things in one module belong together.
  • Low coupling: modules don't depend too heavily on each other's inner details — they talk through clean functions.

If changing one file forces you to edit five others, your modules are too tightly coupled. Aim for pieces you can change independently.

✅ What you learned

  • Split big programs into modules (files) and packages (folders).
  • Use import to reuse code.
  • Separation of concerns — one module, one job.
  • Aim for high cohesion and low coupling.