Topic 11 of 64
Modules & Packages
Overview
Python's module system organizes code into reusable files. Packages are directories of modules. Understanding imports, the standard library, and third-party packages (via pip) is fundamental for any Python project.
Syntax
python
# Importing
import os
import os.path
from datetime import datetime, timedelta
from pathlib import Path
import json as j # alias
# Standard library highlights
import os # OS operations
import sys # Python runtime
import re # regex
import json # JSON
import csv # CSV
import math # math functions
import random # randomness
import time # timing
import datetime # dates
import collections # Counter, defaultdict, deque
import itertools # product, combinations, chain
import functools # lru_cache, partial, wraps
# Package structure
# myproject/
# __init__.py
# models/
# __init__.py
# user.py
# services/
# __init__.py
# auth.pyCommon Pitfalls
- Circular imports cause ImportError — if module A imports from B and B imports from A, restructure your code.
- from module import * pollutes the namespace — always be explicit about what you import.
- Interview tip: __init__.py makes a directory a package in Python 3.3+ (namespace packages work without it, but explicit is better).
Real-World Example
Organizing a web scraper project with proper package structure:
example
python
# scraper/__init__.py
from .core import Scraper
from .utils import clean_text, extract_price
# scraper/core.py
import requests
from bs4 import BeautifulSoup
from .utils import clean_text
class Scraper:
def __init__(self, base_url: str):
self.base_url = base_url
self.session = requests.Session()
def get_page(self, url: str) -> BeautifulSoup:
res = self.session.get(url, timeout=10)
res.raise_for_status()
return BeautifulSoup(res.content, "html.parser")
# main.py
from scraper import Scraper
from scraper.utils import extract_price
scraper = Scraper("https://example.com")
page = scraper.get_page("/products")