7. Modules, Standard Library & Packages
Modules, Standard Library & __name__ == '__main__'
Organize multi-file Python codebases cleanly: master import styles, explore Python's built-in Standard Library (math, random, datetime, pathlib, Counter), and understand if __name__ == '__main__':.
- Split growing programs cleanly into multiple Python files and import between them
- Solve everyday math, date, path, and counting tasks with Python's Standard Library
- Protect runnable scripts cleanly using if __name__ == '__main__':
Putting 2,000 lines of Python inside a single main.py quickly turns into a tangled wall of code. Professional Python projects break responsibilities across separate .py files called modules—and lean heavily on Python's huge built-in Standard Library before installing external packages.
Splitting Code Across Your Own .py Files (import)
Suppose you save reusable helper functions inside pricing.py:
# pricing.py
def with_tax(price: float, rate: float = 0.08) -> float:
return round(price * (1 + rate), 2)In a second file sitting in the same folder (app.py), you can import and reuse with_tax using any of these three clear styles:
| Import Syntax | How You Call It | Best Used When... |
|---|---|---|
import pricing | pricing.with_tax(20) | Keeping clear origin (math.sqrt, json.dumps) prevents name clashes |
from pricing import with_tax | with_tax(20) | You call one or two specific helpers frequently |
import datetime as dt | dt.date.today() | A long module name benefits from a clean team-standard alias |
If you save your practice script as random.py or json.py and write import random, Python imports your own file instead of Python's built-in module—causing baffling AttributeError bugs! Always give your files descriptive project names like dice_game.py.
What if __name__ == "__main__": Actually Means
You will see this mysterious two-line guard at the bottom of almost every real Python file:
def calculate_grade(score: int) -> str:
return "Pass" if score >= 70 else "Retry"
if __name__ == "__main__":
# Runs ONLY when you run `python3 grades.py` directly!
print(calculate_grade(85))Why does it exist?
- When you run
python3 grades.pydirectly in your terminal, Python sets the special hidden variable__name__to"__main__", so the test block runs! - When another file imports your helper (
from grades import calculate_grade), Python executes the file to loadcalculate_grade, but sets__name__to"grades"—so theif __name__ == "__main__":block politely stays silent instead of printing unwanted demo output during imports!
Python's "Batteries-Included" Standard Library
Before running pip install, check whether Python already ships the tool out of the box:
| Built-In Module | Real-World Superpower | Everyday Example |
|---|---|---|
math | Rounding, square roots, pi, trigonometry | math.ceil(4.2) → 5, math.sqrt(81) → 9.0 |
random | Shuffling cards, picking winners, dice rolls | random.choice(["A", "B", "C"]), random.randint(1, 6) |
datetime | Today's date, formatting dates, day math | date.today() + timedelta(days=7) |
pathlib | Cross-platform Windows/Mac file paths (/ safe!) | Path("notes") / "study.txt" |
collections | Instant frequency counting with Counter | Counter(["py", "sql", "py"]) → {'py': 2, 'sql': 1} |
Try It Yourself: Standard Library Combo
Run the playground below to test math, datetime, random, and collections.Counter working together—no installations needed:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Import Counter from collections and count how many times each letter appears in "mississippi", then print the top 2 most common letters using .most_common(2).
Quick Checkpoints
Why do Python developers put script execution code inside if __name__ == '__main__':?
Which built-in Python module lets you count how many times each word appears in a list in one line?