Skip to main content

Modules & Packages

Real-world Python projects aren’t single files. They are split across multiple files (modules) and directories (packages). Understanding how to organize code and manage dependencies is crucial.

1. Modules

A Module is simply a Python file (.py). Any Python file can be imported by another.
# math_utils.py
def add(a, b):
    return a + b

PI = 3.14159

Importing

You can import the whole module or specific parts.
# main.py

# Option 1: Import entire module
import math_utils
print(math_utils.add(1, 2))

# Option 2: Import specific items (Cleaner)
from math_utils import add, PI
print(add(1, 2))

# Option 3: Alias (Common for libraries like pandas as pd)
import math_utils as mu
print(mu.PI)

__name__ == "__main__"

This is a common idiom. It checks if the file is being run directly (like python main.py) or imported.
if __name__ == "__main__":
    print("This code runs ONLY if you execute this file directly.")
    print("It does NOT run if you import this file.")

2. Packages

A Package is a directory containing Python modules. Historically, it required a __init__.py file (though Python 3.3+ makes this optional, it’s still good practice).
my_package/
    __init__.py  # Marks this folder as a package
    module1.py
    module2.py
from my_package import module1
from my_package.module2 import some_function

3. The Standard Library

Python is famous for being “Batteries Included”. It has a massive standard library built-in.

pathlib (Modern File Paths)

Stop using os.path.join. Use pathlib. It works on Windows, Mac, and Linux seamlessly.
from pathlib import Path

# Create path
p = Path("data") / "file.txt"

# Read text
if p.exists():
    content = p.read_text()

# Find files
for file in Path(".").glob("*.py"):
    print(file)

json (Data Serialization)

JSON is the language of the web. Python handles it natively.
import json

data = {"name": "Alice", "age": 30}

# Serialize to String
json_str = json.dumps(data)

# Save to File
with open("data.json", "w") as f:
    json.dump(data, f)

datetime (Dates & Times)

from datetime import datetime, timedelta

now = datetime.now()
tomorrow = now + timedelta(days=1)

print(now.strftime("%Y-%m-%d"))

4. Virtual Environments (venv)

The Golden Rule of Python: Never install packages globally. Always use a virtual environment. A virtual environment creates an isolated folder for your project’s dependencies. This prevents “Dependency Hell” where Project A needs Library v1.0 and Project B needs Library v2.0.

Setup

# 1. Create the environment (run once)
# This creates a folder named 'venv'
python -m venv venv

# 2. Activate it
# Windows:
venv\Scripts\activate
# Mac/Linux:
source venv/bin/activate
Once activated, your terminal prompt will change (e.g., (venv) C:\Project>). Now, when you run pip install, packages go into this folder, not your system.

5. Package Management (pip)

pip is the package installer for Python. It fetches packages from PyPI (Python Package Index).
# Install a package
pip install requests

# List installed packages
pip list

# Save your dependencies to a file
pip freeze > requirements.txt

# Install dependencies from a file (Crucial for collaboration)
pip install -r requirements.txt

Example: Using requests

requests is the most popular Python library. It makes HTTP requests simple.
import requests

response = requests.get("https://api.github.com")
print(response.status_code)
print(response.json())

Summary

  • Modules: .py files.
  • Packages: Folders with __init__.py.
  • Standard Library: Learn pathlib, json, datetime.
  • venv: Always isolate your projects.
  • pip: The tool to install external libraries.
Next, we’ll tackle Advanced Python concepts like decorators and async programming.