Skip to content
beginner Phase 11 · Python Modules & Packages

Modules & Imports

Organize code with modules, __init__.py, and import mechanisms.

45m
0 problems
Topic Progress 0%

How Import Resolution Works

How Import Resolution Works

When Python executes import json, the file is not re-read every time. The import system checks sys.modules first; a hit binds the cached object. On a miss it searches sys.path in order — script directory (or cwd), PYTHONPATH entries, stdlib, then site-packages — and runs the module's top-level code exactly once.

Three rules follow from this:

  • Top-level code runs at import time, so side effects belong under if __name__ == "__main__":
  • import a.b binds the name a; from a.b import c binds c
  • __name__ equals "__main__" only when the file is executed directly

Building and Running Modules

Building and Running Modules

A module is any .py file. Keep the public surface explicit:

# geometry.py
__all__ = ["area"]          # exports for `from geometry import *`
_INTERNAL_SIDES = 3         # underscore prefix = private by convention

def area(r: float) -> float:
    return 3.14159 * r * r

if __name__ == "__main__":
    print(area(2))          # runs only when executed directly

Run entry points with python -m package.module so imports resolve with the same package context they will have in production. Extra search paths come from PYTHONPATH=extras python app.py or an explicit sys.path.insert before importing — never from IDE-only settings that teammates lack.

Pitfalls and Interview Angles

Pitfalls and Interview Angles

Circular imports. a imports b, which imports a. Python leaves the partially initialized module in sys.modules, surfacing AttributeError or ImportError: cannot import name .... Fixes: move the import inside the function, extract shared code into a third module, or invert the dependency.

Shadowing. A local json.py wins over the stdlib because the script directory leads sys.path.

Interview angle: walk the resolver order (cache → sys.path entries → failure), explain why importing a module twice is cheap, why from module import * breaks static analysis, and what executes at import time versus call time.

Quiz

1. What happens the second time a module is imported in the same process?

Question 1 options

2. Where should code that runs only when a file is executed directly be placed?

Question 2 options

3. A module imports b, b imports a, and you get "cannot import name". What is the cause?

Question 3 options

Flashcards

Question

sys.modules

Answer

Dict of already-imported modules; imports check it before searching sys.path.

Question

sys.path search order

Answer

Script dir (or cwd), PYTHONPATH entries, stdlib, site-packages — first match wins.

Question

__name__ == "__main__"

Answer

True only when the file runs directly; guards script-only side effects.

Question

python -m pkg.mod

Answer

Runs the module as __main__ while keeping package context for imports.

Revision Notes

Key Takeaways

  • 1. Imports run module code once; everything after that binds from the sys.modules cache
  • 2. Search order is script dir → PYTHONPATH → stdlib → site-packages, and local files can shadow stdlib
  • 3. Guard executable code with the __main__ check and launch packages with python -m

Interview Tips

  • • Describe the full resolution path: sys.modules hit, then each sys.path entry, then ModuleNotFoundError
  • • Explain circular-import failures as partially initialized modules, then name the refactor that fixes them

Cheat Sheet

import → sys.modules cache → sys.path (script dir, PYTHONPATH, stdlib, site-packages); guard with main; run via python -m; no star imports.

Continue Learning