⚙️
Intermediate
import · from · pip · __all__ · __init__.py
Week 3 — Modules & Packages
Organize code into reusable modules and packages. Understand how Python's import system works, create your own packages, and manage dependencies with pip.
modulepackageimportpip__init__
Duration
⏱ 2 hours
Level
📊 Intermediate
Prerequisite
🎯 Basic Week 9
OUTCOME
Create a multi-file package with a public API defined via __all__
What you'll learn
- 1Import standard library modules and third-party packages
- 2Create your own module (.py file) and import it
- 3Organise a package with __init__.py
- 4Control public API with __all__
- 5Install and use third-party packages with pip
1. Importing Modules
python
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...
from math import sqrt, pi
print(sqrt(25)) # 5.0
import math as m # alias
print(m.factorial(5)) # 1202. Creating a Module
Any .py file is a module. Create utils.py and import from it.
python
# utils.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
# main.py
from utils import greet, PI
print(greet("Alice"))
print(PI)3. Packages
A package is a directory with an __init__.py file. It groups related modules.
text
mypackage/
__init__.py # makes it a package
geometry.py # module with shapes
statistics.py # module with statspython
from mypackage import geometry
from mypackage.statistics import mean4. pip
bash
pip install requests # install
pip install requests==2.31.0 # specific version
pip uninstall requests # remove
pip list # show installed
pip freeze > requirements.txt # export for sharing
pip install -r requirements.txt # install from file5. Common Mistakes
- Circular imports: A imports B, B imports A. Restructure to break the cycle.
- Naming your file the same as a standard library module (e.g., random.py) shadows it.
- from module import * pollutes the namespace. Use explicit imports or __all__ in the module.
💻 Examples
Run these examples and check the output yourself.
geometry.py— A simple geometry module
CODE
"""Geometry helpers."""
import math
__all__ = ["circle_area", "rect_area", "distance"]
def circle_area(r):
return math.pi * r ** 2
def rect_area(w, h):
return w * h
def distance(p1, p2):
return math.sqrt((p2[0]-p1[0])**2 + (p2[1]-p1[1])**2)
main.py— Using the geometry module
CODE
from geometry import circle_area, rect_area, distance
print(f"Circle r=5: {circle_area(5):.2f}")
print(f"Rect 4×6: {rect_area(4, 6)}")
print(f"Distance: {distance((0,0),(3,4)):.2f}")
▶ Output
Circle r=5: 78.54
Rect 4×6: 24
Distance: 5.00📝 Exercises
Try them yourself first, then open the solution to compare.
Exercise 1
math_utils package
Goal: Create a package with two modules: algebra.py and stats.py.
Requirements
- algebra.py: quadratic(a,b,c) returns both roots
- stats.py: mean, median, mode
- __init__.py exports all four functions
- Test from a separate main.py
▶Toggle solution
SOLUTION
# math_utils/__init__.py
from .algebra import quadratic
from .stats import mean, median, mode
# math_utils/algebra.py
import cmath
def quadratic(a, b, c):
d = cmath.sqrt(b**2 - 4*a*c)
return (-b+d)/(2*a), (-b-d)/(2*a)
# math_utils/stats.py
from statistics import mean, median, mode
Example code / lecture materials
All lecture materials and example code are openly available on GitHub.
View on GitHub ↗