0% complete

Functions, modules, and error handling · Lesson 3 of 3

Modules, packages, and imports

Split a program into reusable modules and avoid import-time side effects.

Lesson

1. Concept and mental model

A module is a Python file that defines reusable functions, classes, or constants. A package groups related modules and gives them a clear namespace. Imports should communicate dependencies explicitly: from pathlib import Path makes a commonly used class available by name, while import pathlib keeps its origin visible. Avoid wildcard imports because they make it difficult to see where names came from and can overwrite local names.

2. How it works

Python executes a module’s top-level statements the first time it is imported. Put reusable definitions at module level, but place command-line startup behavior behind if __name__ == '__main__':. This guard lets the file work as both an importable module and a directly run script. Do not perform expensive network calls or modify files merely because another module imported the file.

3. Use it safely and effectively

Use a package structure that reflects responsibilities rather than creating many tiny files without a clear boundary. Be careful not to name your own files after standard-library modules such as json.py or typing.py; doing so can shadow the real module and cause confusing import failures. Practice by separating calculation functions from the command-line entry point and testing the functions without launching the entire program.

4. Syntax reference

def main() -> None:
    print('Run the application')

if __name__ == '__main__':
    main()

5. Guided walkthrough

Place reusable definitions in a module, import only the names the caller needs, and keep startup actions inside a main function. Run the module directly to start the application; importing it from tests should define functions without unexpectedly changing files or calling services.

6. Common mistakes to avoid

  • Running network requests or other side effects at module import time.
  • Naming a project file json.py, typing.py, or another standard-library name and shadowing the real module.

Visual guide

Import and run a module

  1. Step 01 Import

    Load reusable definitions without starting the app.

  2. Step 02 Execute

    Run the guarded entry point directly.

  3. Step 03 Reuse

    Call imported functions from tests or other modules.

Code examples

Worked example
PYTHON
def main() -> None:
    print('Run the application')

if __name__ == '__main__':
    main()
Expected output
Run the application when this file is executed directly.
Import a module with its namespace
PYTHON
import math

print(math.ceil(4.2))
Expected output
5
Expose an explicit public function
PYTHON
from pathlib import Path

def count_lines(path: Path) -> int:
    return len(path.read_text().splitlines())
Expected output
Defines a reusable function without reading a file during import.

Key points

  • Split a program into reusable modules and avoid import-time side effects.
  • Prefer explicit, testable behavior over hidden side effects.
  • Validate assumptions at system boundaries and handle failure deliberately.

Check your understanding

Practice

What does the __main__ guard help prevent?

Your learning progress

Finish this lesson