Python · Module 06: Modules, Files & Error HandlingTutorial 16 of 30
All Tutorials·~1.5 hrs

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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 .py file (like math_utils.py) whose functions and classes you can reuse with import.
  • A Package is a folder of modules (often containing an __init__.py file) grouped by feature (like payments/).
PYTHON
# 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!

Visual: Why `if __name__ == "__main__":` Protects Reusable Modules
1. Run directly: python math_utils.py__name__ == "__main__" ✓Code inside `if __name__ == "__main__":` RUNS!Great for CLI entrypoints & quick tests2. Imported: import math_utils__name__ == "math_utils"Main block is SKIPPED automatically!Only functions & classes are imported cleanly
PYTHON
# 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:

ModuleWhat It Gives YouQuick Example
mathTrigonometry, ceilings, gcd, isclosemath.ceil(4.2) → 5
randomShuffling, random picks, samplingrandom.choice(["A", "B"])
datetimeDates, timestamps, time deltasdatetime.now().isoformat()
pathlibCross-platform file & folder pathsPath("data") / "users.json"
collectionsCounter, defaultdict, dequeCounter("banana")
json / csvParse & save structured datajson.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:

BASH
# 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__

Tracing Running vs. Importing a Module
Interactive Line-by-Line Execution Trace · Step 1 of 4
1→def greet(user):
2 return f"Hello, {user}!"
3if __name__ == "__main__":
4 msg = greet("Riya")
5 print(msg)
Variables in Memory
__name__"__main__"str
greet<function>func
Console Output
(nothing printed yet)
What just happened: You ran `python greet.py` directly, so Python sets __name__ to "__main__" and defines greet().

Quick Quiz: Module 6.1 — Modules, venv & pip

Q1.When `utils.py` is imported by `app.py` via `import utils`, what is `__name__` inside `utils.py`?
Q2.Why should every Python project use a virtual environment (`.venv`)?
Q3.Why is `from math import *` discouraged in production Python?

Keep Exploring: Related Lessons & Tools

All Courses →