Modules, Packages & pip
Organize code into modules, install third-party libraries, and isolate projects with virtual environments.
Modules: what and why
Once a script grows past a few hundred lines, you want to split it. A module is just a `.py` file. Anything you define in it — functions, classes, variables — can be imported and used from another file. This is how programs scale: small, focused files that import from each other.
# math_utils.py
def square(x):
return x * x
PI = 3.14159
# main.py
from math_utils import square, PI
print(square(5), PI)
# Or import the whole module under a name
import math_utils as mu
print(mu.square(5))Packages
A package is a directory containing modules, plus a special file named `__init__.py` (which can be empty). Packages let you nest modules in a hierarchy: `myapp.core.config` instead of one giant file.
myapp/
├── __init__.py
├── core/
│ ├── __init__.py
│ └── config.py
└── api/
├── __init__.py
└── routes.pyThe standard library
Python ships with a huge standard library — modules for math, dates, file paths, networking, regular expressions, JSON, and much more. "Batteries included" is the slogan. Before you reach for a third-party package, check the stdlib.
import math
import json
from datetime import datetime, timedelta
from collections import Counter
from pathlib import Path
print(math.sqrt(2))
print(json.dumps({"a": 1, "b": [1, 2, 3]}))
print(datetime.now() + timedelta(days=7))
print(Counter("mississippi"))
print(Path("data") / "input.csv")pip — installing third-party packages
`pip` is Python's package installer. It downloads packages from the Python Package Index (PyPI) — over 500,000 of them, covering every imaginable use case. Some examples: `requests` for HTTP, `numpy` for numerical arrays, `flask`/`fastapi` for web servers, `pytest` for testing.
pip install requests
pip show requests # info about an installed package
pip list # everything installed
pip uninstall requestsVirtual environments
Every Python project should have its own isolated set of packages. Without that isolation, project A might need `requests` 2.20 while project B needs 2.31, and they fight. A virtual environment (venv) is a per-project copy of Python and its packages — completely independent.
# Create a venv in a folder named .venv
python -m venv .venv
# Activate it
source .venv/bin/activate # macOS / Linux
.venv\Scripts\activate # Windows
# Install dependencies INTO the venv
pip install requests fastapi uvicorn
# Save them so others can reproduce your setup
pip freeze > requirements.txt
# Later, on a fresh machine
pip install -r requirements.txt