Python - Modules

Overview

Estimated time: 25–35 minutes

Structure code with modules and packages. Learn import styles, the module search path, and package layout.

Learning Objectives

  • Import modules and names with import and from ... import ....
  • Understand the module search path and relative imports.
  • Create a simple package and use __init__.py.

Prerequisites

Import styles

import math
from math import sqrt
from collections import defaultdict as dd

print(math.pi, sqrt(16), dd(int))

Package structure

# project/
#   app/
#     __init__.py
#     util.py
#   main.py

# main.py
from app.util import greet
print(greet("Ada"))

Relative imports (inside packages)

# In app/service.py
from .util import greet   # relative import within the same package

Common Pitfalls

  • Running a module inside a package directly (affects __package__). Prefer python -m package.module.
  • Using relative imports from a top-level script (use absolute or run as a module).

Checks for Understanding

  1. What file marks a directory as a package (pre-3.3 and for explicit packages)?
  2. How do you run a module as a script?
Show answers
  1. __init__.py
  2. python -m package.module

Exercises

  1. Create a package with two modules and import between them using a relative import.
  2. Demonstrate running a module with -m and explain the difference from running the file path.