The Import System

Python 3.14 · ✓ verified by execution on 2026-07-31

Welcome back to the Expert level!

To beginners, the import statement in Python seems like magic. You type import math, and suddenly a .py file from somewhere on your hard drive is evaluated and bound to the name math in your local scope.

But what if you want to import a module that doesn’t exist on disk? What if you want to import a module directly from a database, or a network request, or an encrypted ZIP file?

The Import Lifecycle

When you execute import foo, Python goes through a highly structured pipeline:

  1. The Cache Check (sys.modules): Python first checks if foo is already in the sys.modules dictionary. If it is, the import system halts and returns the cached object instantly.
  2. The Finders (sys.meta_path): If it’s a cache miss, Python iterates through the finders (classes) listed in sys.meta_path. Each finder is asked to locate the module by returning a ModuleSpec.
  3. The Loaders: The ModuleSpec contains a Loader object. The loader is responsible for taking the spec and actually executing the code into a new module namespace.

Hijacking sys.meta_path

By writing a custom MetaPathFinder and Loader, you can completely hijack this process.

Let’s look at a concrete example that imports a module directly from a Python dictionary string in memory, completely bypassing the filesystem!

python · visualize
import sys
import importlib.abc
import importlib.machinery
import types

# 1. The Loader executes the code string
class StringLoader(importlib.abc.Loader):
    def __init__(self, code_str):
        self.code_str = code_str

    def exec_module(self, module):
        code = compile(self.code_str, '<string>', 'exec')
        types.FunctionType(code, module.__dict__)()

# 2. The Finder checks if the requested module is in our dictionary
class StringFinder(importlib.abc.MetaPathFinder):
    def __init__(self, modules):
        self.modules = modules

    def find_spec(self, fullname, path, target=None):
        if fullname in self.modules:
            return importlib.machinery.ModuleSpec(fullname, StringLoader(self.modules[fullname]))
        return None

# 3. Register our hook at the front of the meta path!
my_modules = {
    'fake_module': 'def hello(): return "Hello from memory!"'
}
sys.meta_path.insert(0, StringFinder(my_modules))

# 4. Trigger the import machinery!
import fake_module
print(fake_module.hello())

Notice that fake_module.py never existed on disk!

Mastering this API allows you to build highly sophisticated plug-in architectures for your applications.

Check yourself

What happens when you import a module for the second time in a Python process?

Reveal answer

Python checks `sys.modules`, finds the cached module object, and immediately returns a reference to it. — The very first place the import system checks is `sys.modules`. If the module is already cached there, it skips the entire finding and loading process.

How can you intercept all imports in Python to load modules from a custom location (like a database or network)?

Reveal answer

By writing a custom `MetaPathFinder` class and inserting it into `sys.meta_path`. — `sys.meta_path` contains the finders that dictate how Python locates code. Inserting a custom finder allows you to completely hijack the import mechanics.

What is an implicit namespace package (PEP 420)?

Reveal answer

A package that spans multiple directories and does not require an `__init__.py` file. — Since Python 3.3, directories without `__init__.py` files can be treated as namespace packages, allowing you to split a single logical package across multiple physical paths on disk.

Challenges

Challenge 1 +100 XP

Write a `StringFinder` class that implements `find_spec(fullname, path, target=None)`. If `fullname == 'magic'`, it should return a spec using a custom `StringLoader` (provided). Register it in `sys.meta_path` and `import magic`. Print `magic.secret`.

python
  • Test 1 — expects "42\n"
Show solution (0 XP)
import sys, types
import importlib.abc, importlib.machinery

class StringLoader(importlib.abc.Loader):
    def exec_module(self, module):
        code = compile('secret = 42', '<string>', 'exec')
        types.FunctionType(code, module.__dict__)()

class StringFinder(importlib.abc.MetaPathFinder):
    def find_spec(self, fullname, path, target=None):
        if fullname == 'magic':
            return importlib.machinery.ModuleSpec(fullname, StringLoader())
        return None

sys.meta_path.insert(0, StringFinder())
import magic
print(magic.secret)

Challenge 2 +100 XP

Write a function `safe_import(module_name)` that uses `importlib.util.find_spec` to check if a module exists. If it exists, use `importlib.import_module` to import and return it. If it doesn't exist, return `None`. Call it on 'math' and print its `__name__`.

python
  • Test 1 — expects "math\n"
Show solution (0 XP)
import importlib
import importlib.util

def safe_import(module_name):
    spec = importlib.util.find_spec(module_name)
    if spec is not None:
        return importlib.import_module(module_name)
    return None

m = safe_import('math')
print(m.__name__)