๐Ÿ  VisualStudioTutor.com  ยท  Python Tutorial Home  ยท  Python Lesson 7 of 40
Lesson 7 of 40 Foundations Beginner โฑ 25 min

Modules, Packages & pip

Organise Python code into modules and packages, use __init__.py, manage dependencies with pip and uv, and understand the import system.

Part 1: Creating Modules

# mathutils.py
def add(a, b): return a + b
def factorial(n): return 1 if n<=1 else n*factorial(n-1)
PI = 3.14159265

# main.py
import mathutils
from mathutils import factorial, PI
from mathutils import * # avoid โ€” pollutes namespace

Part 2: Package Structure

myapp/
โ”œโ”€โ”€ __init__.py # marks folder as package
โ”œโ”€โ”€ models.py
โ”œโ”€โ”€ services/
โ”‚ โ”œโ”€โ”€ __init__.py
โ”‚ โ””โ”€โ”€ auth.py
โ””โ”€โ”€ utils/
โ””โ”€โ”€ helpers.py

# Import from subpackage
from myapp.services.auth import verify_token

Part 3: pip & pyproject.toml

# pyproject.toml (modern standard)
[project]
name = "myapp"
version = "1.0.0"
requires-python = ">=3.13"
dependencies = [
    "fastapi>=0.115",
    "pydantic>=2.0",
]

# Install project + deps
pip install -e .

Part 4: The if __name__ == "__main__" Pattern

# utils.py โ€” importable AND runnable
def compute(x):
    return x ** 2

if __name__ == "__main__":
    # Only runs when executed directly
    # NOT when imported as a module
    print(compute(10)) # 100
๐Ÿ“˜ Want the complete guide with projects? Get the book โ†’