logo
37

Modules

⏱️ 25 min

Modules: From Single-File Scripts to Maintainable Projects

What might confuse you right now

"A single file works fine. Why split into modules?"

Because once a project grows, one big file becomes hard to search, hard to test, and hard to collaborate on. Modularization is the first step toward engineering discipline.

One-line definition

A module is just a .py file that can be imported and reused.

Real-life analogy

Like organizing a kitchen into zones: knives, spices, sink area. Split by responsibility, and both efficiency and maintainability go up.

Minimal runnable example

mymath.py

def add(a, b):
    return a + b

PI = 3.14159

main.py

import mymath

print(mymath.add(2, 3))
print(mymath.PI)

Common import styles

from mymath import add
print(add(10, 20))

import mymath as mm
print(mm.add(1, 2))

Tips for splitting modules

  • Split by functional responsibility (e.g., string_utils.py)
  • Keep each module focused on one topic
  • Don't name your file the same as a standard library module (e.g., don't create random.py)

Quick quiz (5 min)

  1. Create mymath.py and import it in main.py.
  2. Add sub/mul functions and verify.
  3. Re-run using aliased imports.

Quiz answer guidelines & grading criteria

  • Answer direction: working code that covers core conditions and edge inputs from the prompt.
  • Criterion 1 (Correctness): Main flow produces correct results, key branches execute.
  • Criterion 2 (Readability): Clear variable names, no excessive nesting.
  • Criterion 3 (Robustness): Basic protection against null values, type errors, or unexpected input.

Transfer task (homework)

Take one of your 100+ line scripts and split it into "input module, processing module, output module."

Acceptance criteria

You can independently:

  • Create and import custom modules
  • Distinguish between import x and from x import y
  • Split file structure by responsibility

Common errors & debugging steps (beginner edition)

  • Can't understand the error: read the last line for the error type (e.g., TypeError, NameError), then trace back to the relevant code line.
  • Not sure about a variable's value: temporarily add print(variable, type(variable)) at key points to verify data matches expectations.
  • Code changes aren't taking effect: confirm the file is saved, you're running the right file, and your terminal environment (venv) is correct.

Common misconceptions

  • Misconception: Naming a module the same as a standard library module is fine.

  • Reality: It'll cause import errors. Always avoid standard library names.

  • Misconception: Using from x import * everywhere.

  • Reality: Hurts readability and risks namespace pollution.