Lab 10: Modules & Packages

🎯 Objective

Understand Python's module system — importing stdlib modules, creating your own modules, organizing code into packages, and managing dependencies with pip.

📚 Background

Python ships with a "batteries included" standard library of 200+ modules. Modules are .py files; packages are directories with __init__.py. The import system lets you use code from other files. PyPI (Python Package Index) hosts 500,000+ third-party packages installable via pip. Understanding modules is fundamental to building real Python projects.

⏱️ Estimated Time

30 minutes

📋 Prerequisites

  • Lab 9: Error Handling

🛠️ Tools Used

  • Python 3.12

🔬 Lab Instructions

Step 1: Importing Standard Library Modules

📸 Verified Output:

Step 2: Key Standard Library Modules

📸 Verified Output:

Step 3: datetime Module Deep Dive

📸 Verified Output:

Step 4: Creating Your Own Module

📸 Verified Output:

Step 5: Import Styles and __name__

📸 Verified Output:

Step 6: itertools — Powerful Iteration Tools

📸 Verified Output:

Step 7: functools — Higher-Order Functions

📸 Verified Output:

Step 8: Installing and Using Third-Party Packages

📸 Verified Output:

✅ Verification

Expected output:

🚨 Common Mistakes

  1. Circular imports: Module A imports B which imports A — restructure to break the cycle.

  2. from module import *: Pollutes your namespace with unknown names — import specific names.

  3. Shadowing stdlib names: list = [1,2,3] breaks the built-in list() — avoid it.

  4. Forgetting if __name__ == "__main__":: Code at module level runs on import — guard script code.

  5. pip install without venv: Global pip installs can conflict — always use virtual environments.

📝 Summary

  • import module or from module import name — two import styles

  • Standard library: os, sys, math, datetime, random, re, json, csv, pathlib, itertools, functools

  • if __name__ == "__main__": guards code that should only run as a script

  • @lru_cache memoizes expensive calls; partial() freezes arguments

  • Third-party packages via pip install package_name

  • Always use virtual environments (python3 -m venv .venv) for projects

🔗 Further Reading

Last updated