Skip to content

Beginning of the lesson

Modules and Packages

Split a growing program into files you can reuse, import and ship

Big Idea: A module is simply a .py file. A package is a directory of modules. Instead of one giant script, you organise related code into named files and pull exactly what you need into other files with import. This is how every real Python project — from a 200-line tool to a framework like Django — is structured.
By the end you will be able to:
  • explain what a module is and write your own,
  • use every import form (import, from ... import, as) and know their trade-offs,
  • describe how Python locates a module (sys.path) and what __pycache__ is,
  • use the if __name__ == "__main__": guard correctly,
  • build a package with __init__.py and choose absolute vs relative imports.

1. What exactly is a module?

In the beginner course you called import math and import random — modules that ship with Python. The secret is underwhelming in the best way: a module is just a file of Python code. Any file you save with a .py extension is already a module, and its filename (without .py) is the module name.

Suppose you write geometry.py:

# geometry.py
PI = 3.14159

def circle_area(radius):
    return PI * radius * radius

def rectangle_area(width, height):
    return width * height

From another file in the same folder you can now reuse that code:

# main.py
import geometry

print(geometry.circle_area(2))
print(geometry.PI)

Output:

12.56636
3.14159

The names defined at the top level of geometry.py — PI, circle_area, rectangle_area — become attributes of the module object, reached with dot notation: geometry.circle_area. Modules turn a folder of files into a toolbox you can pick from.

Continue this lesson on YourAIZone

The full lesson has the complete explanation, worked examples, common mistakes, tests with instant checking and an AI tutor. Start right away as a guest, or create an account to keep your progress.

In the full lesson

  • The complete explanation
  • Worked examples
  • Common mistakes and how to avoid them
  • Test questions: 15
  • AI tutor that answers questions about the topic
  • Progress tracking for students, parents and teachers