Lesson · Modules, Packages & Imports
Import System Fundamentals
70 min readImport System Fundamentals
Python's import system searches, loads, executes, and caches modules. Understanding `sys.path`, `sys.modules`, relative imports, and circular imports explains most import problems.
Learning goals
- Describe the four stages of an import: cache check, search, load and execute, cache.
- Read
sys.pathand explain how its order decides which module wins when names collide. - Use
sys.modulesto show that two importers share one module object. - Explain how a circular import leaves a module partially initialized and why moving shared code down fixes it.
- Decide where the boundary sits between what happens at import time and what waits for a call.
Mental model
The chain reads like the code path it describes: the cache answers most lookups immediately, the search list decides where a miss goes next, and each module executes at most once per process before it joins the cache. Circular imports are just this chain running while an earlier link is still unfinished, which is why a module in a cycle can appear half built.
Cache, then search, then execute once
a cache hit returns before anything is searched
Mental model
the same mechanism as a compact list
import name → sys.modules? → search sys.path → load/execute → cache
Core idea
The import system is a cache first and a search second: sys.modules answers by name, and only a miss triggers the finder walk over sys.path and the package paths. The first specification found decides the loader, the module body executes once, and the finished object is stored under its name for every later importer to share. Most import problems are stories about this sequence: a slow body, a shadowed name, or a cycle that imports a module before its own definitions have finished running.
sys.path
sys.path is the ordered list of locations import machinery searches for top-level modules and packages. Environment, invocation style, installation, and tooling can all influence it.
Import search
After checking the module cache, import machinery uses finders to search configured locations and package paths. The first successful module specification determines the loader.
Module cache
Loaded modules are cached in sys.modules. This normally makes repeated imports cheap and ensures callers share the same module object within a process.
sys.modules
sys.modules is the import cache mapping module names to loaded module objects. Re-importing an already loaded module normally reuses this object instead of executing the module again.
Circular imports
A circular import exposes modules while they are only partially initialized. The safest fix is usually to reduce import-time coupling or move shared abstractions to a lower-level module.
Import-time side effects
Importing a module executes its top level in full, so any statement outside a function runs during the import and its effects are paid by the importer. Keep heavy, destructive, or surprising work such as file writes, network calls, or process exits behind a function or the __main__ guard.
Import hooks overview
Import hooks let custom finders and loaders participate in module discovery and loading. They power advanced packaging and runtime systems but are rarely needed in ordinary application code.
Walkthrough
import mathruns the loader once and stores the module under the name"math"insys.modules, soprint("math" in sys.modules)showsTrue(the standard library often has it loaded already, and the import guarantees the entry exists either way).importlib.import_module("math")performs the same lookup programmatically: the cache answers first, so nothing executes a second time.math is same_mathprintsTrue, proving that the import system hands every caller the same module object rather than a copy.sys.path[:3]shows the start of the search list, normally the script's own directory (an empty string in some invocations) followed by standard-library locations. Predict before running: all three printed lines, noting that the path entries depend on the machine.
Experiments to try
- Delete
"math"fromsys.modules, import it again, and explain why the module body runs a second time after the deletion. - Inspect
sys.modules["math"].__name__and compare it with the dictionary key; confirm the cache maps names to module objects. - Append a temporary directory to
sys.path, drop a tiny module there, and import it; then start a new process without the entry and read theModuleNotFoundError. - Reorder
sys.pathso a directory of yours comes first and explain how the earlier entry can shadow a standard-library name.
Playable lesson
Lab: Import system explorer
Visualize sys.modules cache lookup, sys.path search, module execution, and caching. Include a circular import scenario.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Import system explorer
Resolution chain
- import math
the statement begins
- sys.modules?
"math" is found, so nothing re-executes
- bind the name
`math` in the namespace is the cached module
sys.modules
- sys
- builtins
- math
Cached modules are reused; the body never runs twice for the same name.
Predict first
`math` is already in `sys.modules`. What does `import math` do?
`math is importlib.import_module("math")` is True: every caller receives one module object per process.
The trap is assuming a second import re-runs the body. It does not; the cache answers first.
Common mistakes
- Putting expensive or surprising side effects at module import time: the importer pays the cost and the effects surface at a call site that has nothing to do with them.
- Editing
sys.paththroughout application code: the list is process-global, so an entry added for one import changes how every later import resolves and can shadow real packages. - Treating
importlib.reloadas a safe refresh: it reruns the body into the same namespace, so existing references keep the old objects andiscomparisons across the reload returnFalse. - Chasing circular imports with import indirection instead of reducing coupling: the cycle remains, and the failure just moves to an attribute access on a partially initialized module.
Practice: Easy
- Run the worked example and record the three printed lines; then print
len(sys.modules)before and after importing a module of your own and account for the change. - Check
"math" in sys.modulesbefore any explicit import ofmath, then after importing it, and explain the difference you found. - Add a
printto a small local module and import it twice; count the messages and connect the result to the cache.
Practice: Medium
- Run
import importlib; del sys.modules["mymodule"]and thenimportlib.import_module("mymodule")on a module with a top-levelprint; explain why the message appears again after the deletion. - Create a temporary directory with a tiny module, append it to
sys.path, import the module, then start a new interpreter without the entry and describe what differs between the two processes. - Write two modules that import each other at top level and reproduce the partial-initialization error; then break the cycle by moving the shared code into a third module and document the new dependency direction.
Practice: Hard
- Show first-found-wins search in practice: place two same-named modules on
sys.pathin different directories, reorder the entries, and record which one loads in each arrangement. - Reproduce the reload identity problem: import a class from a module, call
importlib.reloadon the module, and show withisthat old and new references are different objects. - Audit a small project for import-time effects: list every top-level action, classify each as definition, configuration, or effect, and move the effects behind functions or guards.
Lesson checklist
- I can describe the four stages an import passes through: cache check, search, load and execute, cache.
- I can explain why two modules that import the same dependency share one module object.
- I can demonstrate that
sys.pathorder decides which module wins when names collide. - I can reduce an import-time side effect or a circular import instead of working around it.
Remember
The import system checks `sys.modules` first, searches `sys.path` in order, executes the first matching module once, and caches the result, which is why imports are cheap, shared, and occasionally surprising. Most import problems come from two places: side effects that ride along with the first execution, and cycles where two modules need each other before either finishes. Fix the coupling, not the symptom, and treat the search path as configuration rather than something application code rewrites.
Interview angles
What is the main purpose of **sys.path**?+
sys.path is the ordered list of locations import machinery searches for top-level modules and packages. Environment, invocation style, installation, and tooling can all influence it.
What should you pay attention to when using **Import search**?+
After checking the module cache, import machinery uses finders to search configured locations and package paths. The first successful module specification determines the loader.
How does **Module cache** fit into this lesson?+
Loaded modules are cached in sys.modules. This normally makes repeated imports cheap and ensures callers share the same module object within a process.
Why is editing `sys.path` from inside application code risky?+
The search list is process-global: an entry added for one import changes how every later import resolves, and an early entry can shadow a standard-library or third-party module with a name collision. Prefer packaging or an explicit entry point over mutating sys.path at runtime.