Loading...
Loading...
import, from, packages, and fixing common errors - everything you need
When you write import foo, Python does not simply look for a file named foo.py on disk. Instead, it follows a well-defined import protocol with multiple stages: checking the module cache, consulting a series of finders, and finally using a loader to execute the module code. Understanding this protocol is essential for debugging import errors and controlling module resolution in larger projects.
The Import Protocol (step by step)
============================================================
import foo
|
v
1. Check sys.modules cache
+---------------------------+
| sys.modules['foo'] |
| exists? |
+---------------------------+
| |
YES NO
| |
v v
Return 2. Iterate sys.meta_path finders
cached |
module v
+-------------------------------+
| for finder in sys.meta_path: |
| spec = finder.find_module() |
| if spec is not None: break |
+-------------------------------+
|
v
3. Finder returns a ModuleSpec
(contains loader, origin, submodule_search_locations)
|
v
4. Loader creates module object
loader.create_module(spec)
|
v
5. Module added to sys.modules
(BEFORE code execution!)
|
v
6. Loader executes module code
loader.exec_module(module)
|
v
7. Bind name in caller's namespace
caller.foo = sys.modules['foo']A critical detail: Python inserts the module into sys.modules in step 5, before executing the module body in step 6. This is what makes circular imports partially work. If module B imports module A while A is still loading, B gets the partially initialized module object from the cache rather than triggering an infinite loop.
Default sys.meta_path Finders (in order)
============================================================
sys.meta_path = [
BuiltinImporter, # 1. Built-in modules (sys, _io, etc.)
FrozenImporter, # 2. Frozen modules (rarely relevant)
PathFinder, # 3. File-system search via sys.path
]
BuiltinImporter
+-----------------------------------------+
| Handles modules compiled into the |
| Python interpreter itself. |
| Examples: sys, _thread, _io, marshal |
| These have no .py file on disk. |
+-----------------------------------------+
|
| not found
v
FrozenImporter
+-----------------------------------------+
| Handles modules frozen into the binary. |
| Used internally by Python's bootstrap. |
| importlib._bootstrap is a frozen module.|
+-----------------------------------------+
|
| not found
v
PathFinder
+-----------------------------------------+
| Searches sys.path entries one by one. |
| For each path entry, consults |
| sys.path_hooks to get a path entry |
| finder (typically FileFinder). |
| FileFinder looks for .py, .pyc, and |
| extension modules (.so / .pyd). |
+-----------------------------------------+