Lab 02: Custom Import System

Time: 60 minutes | Level: Architect | Docker: docker run -it --rm python:3.11-slim bash

Overview

Python's import system is fully customizable. You can intercept import statements to load modules from databases, encrypted files, remote URLs, or generate them synthetically. This lab explores importlib machinery at the architectural level.

Step 1: How Import Works

import sys

# sys.meta_path: list of finders checked in order
print("Meta path finders:")
for finder in sys.meta_path:
    print(f"  {type(finder).__name__}: {finder}")

# sys.path_hooks: factories for path-based finders
print("\nPath hooks:")
for hook in sys.path_hooks:
    print(f"  {hook}")

# sys.modules: already-imported modules cache
print(f"\nCached modules (count): {len(sys.modules)}")
print(f"  'os' cached: {'os' in sys.modules}")

💡 Python checks sys.meta_path finders first, then falls back to sys.path_hooks for filesystem-based imports. Adding to sys.meta_path lets you intercept any import.

Step 2: MetaPathFinder — The Core Interface

Step 3: Custom Loader

A Loader is responsible for creating and populating a module object:

📸 Verified Output:

Step 4: Import Hooks for Encrypted Modules

💡 Real encrypted module systems use AES or Fernet (see Lab 14). The key insight is that exec_module receives a blank module object you populate by executing the decrypted source.

Step 5: Path Entry Finders

Step 6: pkgutil.iter_modules

Step 7: Module Reloading and Isolation

Step 8: Capstone — Plugin Loader System

Build a complete plugin loading system that discovers and loads plugins from a directory:

📸 Verified Output:

Summary

Concept
API
Use Case

MetaPathFinder

find_spec()

Intercept any import

Custom Loader

create_module/exec_module

Load from non-standard sources

sys.meta_path

Insert at index 0

Override import resolution

Encrypted modules

exec(compile(...))

Obfuscated/protected code

pkgutil.iter_modules

Package discovery

Plugin systems

Module sandboxing

types.ModuleType + restricted builtins

Security isolation

Plugin registry

MetaPathFinder + registry

Extensible applications

Last updated