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__':.

4 min readUpdated 2026-11-29
In This Lesson
  • 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:

python
# 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 SyntaxHow You Call ItBest Used When...
import pricingpricing.with_tax(20)Keeping clear origin (math.sqrt, json.dumps) prevents name clashes
from pricing import with_taxwith_tax(20)You call one or two specific helpers frequently
import datetime as dtdt.date.today()A long module name benefits from a clean team-standard alias
Never Name Your Script After a Standard Module

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:

python
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.py directly 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 load calculate_grade, but sets __name__ to "grades"—so the if __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 ModuleReal-World SuperpowerEveryday Example
mathRounding, square roots, pi, trigonometrymath.ceil(4.2) → 5, math.sqrt(81) → 9.0
randomShuffling cards, picking winners, dice rollsrandom.choice(["A", "B", "C"]), random.randint(1, 6)
datetimeToday's date, formatting dates, day mathdate.today() + timedelta(days=7)
pathlibCross-platform Windows/Mac file paths (/ safe!)Path("notes") / "study.txt"
collectionsInstant frequency counting with CounterCounter(["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:

Python 3Try It Live: Python Standard Library Essentials
Output

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

Check Your Understanding

Why do Python developers put script execution code inside if __name__ == '__main__':?

Check Your Understanding

Which built-in Python module lets you count how many times each word appears in a list in one line?