6.1 Modules, Packages, Virtual Environments (venv) & pip
Organize real Python projects cleanly! Learn how imports work, why every script uses if __name__ == '__main__', explore Python's built-in Standard Library, and isolate dependencies with venv + pip.
1. What Are Modules & Packages? (The Toolbox Analogy)
Putting an entire real-world app inside one 3,000-line .py file is like dumping every screwdriver, hammer, and wrench into one messy bucket.
- A Module is simply any
.pyfile (likemath_utils.py) whose functions and classes you can reuse withimport. - A Package is a folder of modules (often containing an
__init__.pyfile) grouped by feature (likepayments/).
# 1) Import the entire module (safest — always clear where functions come from)
import math
print(math.sqrt(49)) # 7.0
# 2) Import specific items directly
from datetime import date
print(date.today()) # e.g. 2026-11-20
# 3) Import with a short alias
import statistics as stats
print(stats.mean([10, 20, 30])) # 20
Beginner Trap: Avoid
from math import *(wildcard import)! It dumps dozens of invisible names into your file and can silently overwrite your own variables.
2. The Magic Line: if __name__ == "__main__":
Almost every real Python file ends with if __name__ == "__main__":. Why?
When Python runs a file directly (python math_utils.py), it sets a special hidden variable __name__ = "__main__". When another file imports it (import math_utils), __name__ is set to "math_utils" instead!
# math_utils.py
def add_tax(price, rate=0.18):
return round(price * (1 + rate), 2)
if __name__ == "__main__":
# Runs ONLY when you execute `python math_utils.py` directly!
# Does NOT run when another file does `import math_utils`!
print("Self-test:", add_tax(100))
3. Python's "Batteries Included" Standard Library
Before installing third-party packages, check Python's built-in Standard Library — it already includes:
| Module | What It Gives You | Quick Example |
|---|---|---|
math | Trigonometry, ceilings, gcd, isclose | math.ceil(4.2) → 5 |
random | Shuffling, random picks, sampling | random.choice(["A", "B"]) |
datetime | Dates, timestamps, time deltas | datetime.now().isoformat() |
pathlib | Cross-platform file & folder paths | Path("data") / "users.json" |
collections | Counter, defaultdict, deque | Counter("banana") |
json / csv | Parse & save structured data | json.dumps({"ok": True}) |
4. Virtual Environments (venv) & pip (Project Isolation)
Imagine Project A needs requests==2.28 and Project B needs requests==2.32. Installing everything globally causes version clashes ("works on my machine!").
A Virtual Environment (.venv) gives each project its own private copy of Python and installed packages:
# 1. Create a virtual environment inside your project folder
python3 -m venv .venv
# 2. Activate it
source .venv/bin/activate # macOS / Linux
# .venv\Scripts\activate # Windows PowerShell
# 3. Install packages & freeze them for teammates
pip install requests pytest
pip freeze > requirements.txt
# 4. Recreate on another machine later
pip install -r requirements.txt
(Always add .venv/ to your .gitignore — never commit thousands of library files to Git!)
5. Interactive Trace: Module Import & __name__
Quick Quiz: Module 6.1 — Modules, venv & pip
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.