A module is a unit of importable Python code. A package organizes related modules under a common import namespace.
Trace module loading, main guards and import paths, then diagnose which module an interpreter actually loads.
An import can load your own random.py instead of the standard library, or expose a module before it has finished defining its names. These failures make more sense when import is treated as execution and caching. Follow one module into the cache, then diagnose which object an import actually found.

Cache a slow module so it only runs once
Steps 2 to 4 of import need nothing but the standard library — done here by
hand, with types.ModuleType, the very type every imported module has:
The body printed once, though load ran twice. With a real file the same
thing happens — the browser has an in-memory filesystem, so this really
imports:
import importlib
import pathlib
import sys
import tempfile
sys.modules.pop("greeter", None)
root = tempfile.mkdtemp()
pathlib.Path(root, "greeter.py").write_text('print("loading", end=" ")\n')
sys.path.insert(0, root)
importlib.invalidate_caches()
import greeter
import greeter
import greeter
print(sys.modules["greeter"] is greeter)Preparing this topic’s interactive investigation…
Guard a script so importing it doesn't rerun main()
Every module has a __name__, set before its first line runs. A file
started with python report.py gets the special name "__main__"; imported,
it gets its dotted name. That's the entire trick behind if __name__ == "__main__"::
Run as a script, the guarded block calls main(). Imported, the file only
defines main and leaves calling it to whoever imported it. Without the
guard, merely importing the module would build a report as a side effect,
every time:
import types
report = types.ModuleType("quarry.report")
exec("where = __name__.rpartition('.')[2]", report.__dict__)
print(report.where)Reach the vault from a sibling package
Fourteen modules in one flat folder is hard to navigate. A package
groups them — a folder with an __init__.py — and the folder's name becomes
part of every file's dotted name:
quarry/
├── __init__.py → quarry
├── cli.py → quarry.cli
├── stages/
│ ├── __init__.py → quarry.stages
│ └── parse.py → quarry.stages.parse
└── store/
├── __init__.py → quarry.store
└── vault.py → quarry.store.vaultA package is a module — quarry has a __dict__ and a body, which is its
__init__.py — and importing anything inside it runs every __init__.py
above it first, because quarry.store.vault cannot exist until quarry
and quarry.store do:
quarry/stages/parse.py can reach the vault two ways: from quarry.store import vault (absolute) or from ..store import vault (relative — one dot means the current package, and each additional dot
climbs one parent level). Step through the dot arithmetic:
Run cli.py directly and a relative import fails with ImportError: attempted relative import with no known parent package: the file is
__main__, belonging to no package, so the dot has nothing to be relative
to. python -m quarry.cli locates it by its dotted name and executes it as
__main__ with package context, and the
same line works — never make a module work only by running it as a script.
Diagnose the interpreter, the search path and the loaded module
An import failure has several possible causes; installing the package again only addresses some of them. First establish which interpreter is running, which path Python searched, and which module it actually loaded.
Local diagnostic sequence:
import sys
import importlib.util
print(sys.executable)
print(sys.path[0])
spec = importlib.util.find_spec("json")
print(spec.origin if spec is not None else "not found")
import json
print(json.__file__)If json.__file__ points to your project’s json.py, this is shadowing. If a third-party module is not found, check whether it was installed for this same interpreter. If the error says “partially initialized module”, inspect the dependency cycle and the order in which names are defined; that is different from a missing installation. find_spec can import a dotted name's parent, so it is a diagnostic for trusted code, not a side-effect-free sandbox.
sys.modules caches module objects by name. Under ordinary successful imports, repeated imports reuse them; explicit reloading, deletion from the cache and failed imports complicate the “once” shorthand. The examples use regular packages with __init__.py. Python also supports namespace packages without that file, so the exercise's package resolver is a deliberate subset of the real import system.
Repair a dependency direction: suppose cli imports parser, parser imports report, and report imports cli for a constant. Move the shared constant into a small module that imports none of those three. Draw the resulting arrows and explain why importing parser no longer needs a half-built cli. Hiding the cycle with an import inside a function can postpone a failure; changing ownership can remove it.
Reference: module caching, finders and package kinds.
Traps worth knowing
Circular imports. Module a imports b, and b imports a. A module
is cached before its body runs, so when b asks for a, Python hands
back the half-built module, stopped on the line that imported b — anything
below that line doesn't exist yet:
ImportErrorcli imports report, and report imports a name from cli that cli hasn't defined yet. Change report.py's source so it no longer needs VERSION at import time, and the program prints "quarry 0.3".
Shadowing. Name your own file random.py and import random in that
folder finds yours first, silently. Import-time cost is startup cost: a
CLI that eagerly imports 30 stage modules to print --help pays for all of
them — keep module bodies cheap, and import heavy things inside the function
that needs them.
Quick practice
import sys, importlib, pathlib, tempfile
sys.modules.pop("widget", None)
root = tempfile.mkdtemp()
pathlib.Path(root, "widget.py").write_text("COUNT = 0\n")
sys.path.insert(0, root)
importlib.invalidate_caches()
import widget
import widget as w2
w2.COUNT = 99
print(widget.COUNT)Importing this module prints "building report..." as a side effect every time. Move that print under a main guard so importing it stays silent and only 42 prints.
import sys, importlib, pathlib, tempfile
original_random = sys.modules.get("random")
with tempfile.TemporaryDirectory() as root:
pathlib.Path(root, "random.py").write_text("def choice(seq):\n return 'rigged'\n", encoding="utf-8")
sys.path.insert(0, root)
importlib.invalidate_caches()
sys.modules.pop("random", None)
try:
import random
print(random.choice(["a", "b", "c"]))
finally:
sys.path.remove(root)
sys.modules.pop("random", None)
if original_random is not None:
sys.modules["random"] = original_random
importlib.invalidate_caches()🎯 Your turn
Build resolve_import(files, current, statement) — the first piece of
Quarry's shipment. It answers the question every confusing ImportError
hides: what does this line actually load?
fileslists the project's files, relative to the folder onsys.path.currentis the path of the file containing the statement.statementisimport Xorfrom X import Y, whereXmay be relative.
Return the dotted name of the deepest module loaded and the chain of
files Python runs for it, parents first. A folder's __init__.py wins over
a same-named .py file. For from X import Y, if X.Y is itself a module,
it is loaded too; otherwise Y is just a name inside X.
resolve_import(FILES, "quarry/stages/parse.py", "from ..store import vault")
# → {"module": "quarry.store.vault",
# "chain": ["quarry/__init__.py", "quarry/store/__init__.py", "quarry/store/vault.py"]}
resolve_import(FILES, "cli.py", "from . import quarry")
# → {"error": "ImportError"} # no parent package
resolve_import(FILES, "quarry/cli.py", "import quarry.yard.walk")
# → {"error": "ModuleNotFoundError", "name": "quarry.yard"}Press ▶ Run and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Every .py file under a sys.path folder is importable by a dotted name. Write module_name(path) that turns a slash-separated path into that name: "quarry/stages/parse.py" → "quarry.stages.parse", and a package's __init__.py names the package itself: "quarry/stages/__init__.py" → "quarry.stages". Anything that isn't a .py file gives "".
Importing a module runs its source top to bottom in a fresh namespace whose __name__ is the module's name — or "__main__" when the file is run as a script. Write run_as(source, name): run source with exec in a new dict whose __name__ is name, and return the sorted list of names it defined, leaving out any that start with _. Example: a file with a main() function and an if __name__ == "__main__": code = main() guard gives ["code", "main"] as "__main__" but only ["main"] as "quarry.cli".
In a project that uses regular packages, a .py file is importable only if every folder above it holds an __init__.py. Write package_tree(files) returning a dict from each importable dotted name to "package" or "module". A folder with __init__.py is a package (named for the folder); other .py files are modules. Files under a folder chain with a missing __init__.py are left out, and so is anything that isn't .py. Example: ["quarry/__init__.py", "quarry/cli.py"] → {"quarry": "package", "quarry.cli": "module"}.
A circular import is a cycle in the graph of who imports whom at module level. Write find_cycle(imports): imports maps each project module to the list of modules it imports at the top of its file. Imports of names that aren't keys (like json) are outside the project — ignore them. Search depth-first, starting from the module names in sorted order and following each list in the order given, and return the first cycle you close as a list that starts and ends with the same module, e.g. ["quarry.cli", "quarry.report", "quarry.cli"]. Return [] when there is none.
Now do it for real. files maps paths to source text. Write run_package(files, entry, attr): write the files into a fresh temporary folder, put that folder at the front of sys.path, import the dotted module entry with importlib.import_module, and return {"value": <its attribute attr>, "loaded": <sorted names in sys.modules that belong to entry's top-level package>}. If the import raises, return {"error": <the exception's type name>}. Leave no trace: before and after, drop every sys.modules entry for that top-level package, and take your folder back off sys.path. Call importlib.invalidate_caches() after writing files — Python caches folder listings and may not see files made after it looked.
quarry/cli.py starts with from .store import vault. Running python -m quarry.cli works, but python quarry/cli.py stops with ImportError: attempted relative import with no known parent package. Explain what is different about the two ways of starting the same file, and why Quarry's installed quarry command will never hit this error.