arthrop0d

Brief articles on varied topics.

Python Import Machinery and Circular Imports

python

Python’s import machinery is the system that locates Python code, creates a module object, executes it, and caches the result. sys.modules, finders, and loaders are its central pieces: the cache prevents repeated work, finders decide where a module comes from, and loaders execute it.

Why an import system is needed

An import statement could have been defined as “find a file with this name and run it.” That is not enough in a real application. Python also needs to import packages, built-in modules, compiled extension modules, and modules supplied by plugins or custom import hooks. It must avoid executing the same module repeatedly, preserve module identity, and handle dependencies between modules.

Without a shared cache, two parts of a program could load the same file twice and receive different module objects. Class identity, global state, and registration tables could then unexpectedly diverge. Python’s import machinery solves this by keeping loaded modules in sys.modules.

sys.modules: the import cache

sys.modules is a dictionary owned by the running Python interpreter. Its keys are fully qualified module names, such as "json" or "mypackage.database"; its values are the corresponding module objects.

A simplified import begins by checking this dictionary:

import json

If "json" is already in sys.modules, Python normally reuses that module rather than locating and executing it again. This is why importing a module in several files does not rerun its top-level code each time. The import statement binds the existing module to a name in the importing file.

The cache is more than an optimization. It is also how Python represents an import that is currently in progress. Before executing a module’s code, the machinery places that module object into sys.modules. At that point the object is real, but its code may be only partly executed.

That detail is essential for circular imports.

Finders locate a module

If a module is not already cached, Python asks its finders where the module can be obtained. A finder is an object that examines an import request and either declines it or returns a description of how to load it.

Python consults finder objects in sys.meta_path, a list of import hooks. The standard finders handle common sources such as:

sys.path is the list of locations searched for top-level modules. For a package, a package is a module that can contain submodules, Python also searches locations associated with that package.

A successful finder returns a module spec: a record containing information such as the module’s name, its loader, and, for a package, where its submodules can be found. A finder does not normally execute the module. It answers the location question and identifies the next component.

Loaders create and execute

The spec names a loader, the object responsible for turning that description into an initialized module. The import machinery asks the loader to create a module object when the loader provides a custom creation step. Otherwise Python creates the usual module object itself.

It then sets import-related attributes, including __name__, __package__, __spec__, and __loader__. Before running the module, it inserts the object into sys.modules. Finally, it asks the loader to execute the module’s code.

For an ordinary .py file, execution means running its top-level statements from beginning to end. For a built-in or compiled extension, the loader performs the corresponding implementation-specific initialization instead.

The order matters:

  1. Check sys.modules.
  2. Ask finders for a spec.
  3. Create a module object.
  4. Put it in sys.modules.
  5. Execute the module.
  6. Return the now-initialized module to the caller.

If execution fails, Python removes the failing module from sys.modules in the usual import path, although modules it imported successfully can remain cached. This is one reason a failed import can leave observable state elsewhere in a process.

How circular imports fail

Consider two files that require names from each other:

# a.py
from b import value_b

value_a = "A"
# b.py
from a import value_a

value_b = "B"

Now run:

import a

The sequence is:

  1. a is not in sys.modules, so Python finds it, creates its module object, and caches it as sys.modules["a"].
  2. Python starts executing a.py. value_a has not been assigned yet.
  3. a.py imports b. Python creates and caches b as well, then starts executing b.py.
  4. b.py imports a. This time a is already in sys.modules, so Python reuses its partially initialized module instead of starting a second copy.
  5. b.py asks for value_a, but execution of a.py has not reached the assignment that creates it.

The result is commonly an error such as ImportError: cannot import name 'value_a' from partially initialized module 'a'. The phrase partially initialized module describes exactly what happened: the module object exists and is cached, but its top-level code has not finished.

A variation using import a followed later by a.value_a may instead produce an AttributeError, because the module object exists but lacks that attribute at the moment it is accessed. Both errors point to the same ordering problem.

“Partially initialized module” in a traceback is usually a strong signal that an import cycle reached a name before the defining module had finished executing.

The fix is to remove the cycle or delay the dependency. For example, shared constants can move into a third module that both files import. An import needed only inside a function can sometimes be moved there, so it runs after module initialization:

# a.py

def use_b():
    from b import value_b
    return value_b

value_a = "A"

That delay is useful when the dependency is genuinely runtime-specific, but it should not hide a design cycle that would be clearer if the shared code were reorganized.

Once you understand the cache, the finder/loader split, and the early insertion into sys.modules, ordinary import behavior and circular-import tracebacks become two outcomes of the same process—not separate Python quirks.

← All articles