Lesson 7 of 40
Foundations
Beginner
โฑ 25 min
Modules, Packages & pip
Organise Python code into modules and packages, use __init__.py, manage dependencies with pip and uv, and understand the import system.
Part 1: Creating Modules
# mathutils.py
def add(a, b): return a + b
def factorial(n): return 1 if n<=1 else n*factorial(n-1)
PI = 3.14159265
# main.py
import mathutils
from mathutils import factorial, PI
from mathutils import * # avoid โ pollutes namespace
def add(a, b): return a + b
def factorial(n): return 1 if n<=1 else n*factorial(n-1)
PI = 3.14159265
# main.py
import mathutils
from mathutils import factorial, PI
from mathutils import * # avoid โ pollutes namespace
Part 2: Package Structure
myapp/
โโโ __init__.py # marks folder as package
โโโ models.py
โโโ services/
โ โโโ __init__.py
โ โโโ auth.py
โโโ utils/
โโโ helpers.py
# Import from subpackage
from myapp.services.auth import verify_token
โโโ __init__.py # marks folder as package
โโโ models.py
โโโ services/
โ โโโ __init__.py
โ โโโ auth.py
โโโ utils/
โโโ helpers.py
# Import from subpackage
from myapp.services.auth import verify_token
Part 3: pip & pyproject.toml
# pyproject.toml (modern standard)
[project]
name = "myapp"
version = "1.0.0"
requires-python = ">=3.13"
dependencies = [
"fastapi>=0.115",
"pydantic>=2.0",
]
# Install project + deps
pip install -e .
[project]
name = "myapp"
version = "1.0.0"
requires-python = ">=3.13"
dependencies = [
"fastapi>=0.115",
"pydantic>=2.0",
]
# Install project + deps
pip install -e .
Part 4: The if __name__ == "__main__" Pattern
# utils.py โ importable AND runnable
def compute(x):
return x ** 2
if __name__ == "__main__":
# Only runs when executed directly
# NOT when imported as a module
print(compute(10)) # 100
def compute(x):
return x ** 2
if __name__ == "__main__":
# Only runs when executed directly
# NOT when imported as a module
print(compute(10)) # 100
๐ Want the complete guide with projects?
Get the book โ