MOD-22 · Sequence #22 · Advanced Python

Python Modules & Packages

Modules (.py files) and packages (directories with __init__.py) organize code into reusable namespaces. Understanding import mechanics, sys.path resolution, aliases with `as`, and the `if __name__ == "__main__":` idiom is crucial for production code.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
import math as m
print(m.sqrt(16))  # 4.0
print(m.pi)        # 3.14159...

Core Principles & Mental Models

1. Module Import Mechanics and sys.path

How CPython Locates and Caches Modules

  • When you execute `import math`, Python searches directories listed in `sys.path`.
  • Once found, Python compiles the file to bytecode (.pyc in __pycache__), executes the top-level code, and caches the module in `sys.modules`.
  • Subsequent imports of the same module retrieve the cached reference without re-executing.
import sys
print("Current Python sys.path entries:", len(sys.path))
import math as m
print("Square root of 25:", m.sqrt(25))
💡 Key Takeaway: Python caches loaded modules in sys.modules, executing module code only once per process.

2. The `if __name__ == "__main__":` Execution Guard

Script Execution vs. Library Import

  • When a file is run directly by python (`python script.py`), Python assigns `__name__ = "__main__"`.
  • When a file is imported by another module (`import script`), Python assigns `__name__ = "script"`.
  • Wrapping entry points in `if __name__ == "__main__":` ensures tests and scripts only run when directly invoked.
def calculate_average(nums):
    return sum(nums) / len(nums)

if __name__ == "__main__":
    # Only runs when directly executed, not when imported!
    print("Self-test:", calculate_average([10, 20, 30]))
💡 Key Takeaway: Always guard top-level execution code with if __name__ == "__main__":.

Interactive Walkthrough Examples

Selective Imports vs. Wildcard Imports (Basic)

Demonstrating clean selective imports with aliases.

from math import pi, sqrt, floor as fl

print("Pi constant:", round(pi, 4))
print("Floor of 4.9:", fl(4.9))
print("Sqrt of 64:", sqrt(64))

Explanation: Selective imports keep namespaces clean and explicit.

Common Misconceptions & Exam Traps

Common Pitfall: Wildcard Imports (`from module import *`)

Wildcard imports obscure where functions originate and cause silent namespace collisions.

Buggy Code
from math import *  # Pollutes global namespace; can overwrite existing variables silently!
Correct Solution
import math
# or: from math import sin, cos

Exam Trap Note: PEP 8 strictly condemns `from module import *` in production code.

Conceptual Knowledge Self-Check Quiz

Q1: What is the value of `__name__` when a Python file is run directly as the main program?

  1. "__init__"
  2. "__main__"
  3. "main"
  4. The file name

CPython sets the special variable `__name__` to `"__main__"` for the entry-point script.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Place imports at the very top of the file, grouped: Standard library, 3rd party, Local.
  • ✅ Always use `if __name__ == "__main__":` in runnable scripts.

All 26 Curriculum Modules