204. Python’s Import Hooks

🔹 1. Basic Import Hook (Logging Imports)

  • Hooks into Python’s import system to log imports.

import sys

class ImportLogger:
    def find_module(self, fullname, path=None):
        print(f"Importing {fullname}")
        return None  # Let Python handle the import

sys.meta_path.insert(0, ImportLogger())

import math  # Output: Importing math

🔍 How it works:

  • find_module() logs module imports but doesn’t modify them.


🔹 2. Blocking Certain Modules from Being Imported

  • Prevents unwanted modules from being imported.

import sys

class BlockModules:
    def find_module(self, fullname, path=None):
        if fullname in {"os", "sys"}:
            raise ImportError(f"Blocked import: {fullname}")
        return None  # Allow other imports

sys.meta_path.insert(0, BlockModules())

import os  # Raises ImportError

🔍 How it works:

  • Blocks specific modules by raising an ImportError.


🔹 3. Custom Module Loader

  • Loads a module dynamically at runtime.

🔍 How it works:

  • Dynamically creates and loads a module named custom_module.


🔹 4. Importing from a ZIP File

  • Implements a custom import hook to load modules from a ZIP archive.

🔍 How it works:

  • zipimport allows loading Python modules from a ZIP file.


🔹 5. Redirecting Imports

  • Redirects an import to a different module.

🔍 How it works:

  • Any import of math gets replaced by random.


🔹 6. Creating a Read-Only Import Hook

  • Prevents modifications to imported modules.

🔍 How it works:

  • Makes module attributes immutable.


🔹 7. Importing from a Custom Directory

  • Loads modules from a specific directory outside sys.path.

🔍 How it works:

  • Dynamically loads modules from a user-defined directory.


🔹 8. Import Hook for Enforcing Module Naming Conventions

  • Enforces naming conventions for imported modules.

🔍 How it works:

  • Prevents importing modules with uppercase names.


🔹 9. Auto-Reloading Modules on Import

  • Automatically reloads a module when imported.

🔍 How it works:

  • Forces a module to reload every time it’s imported.


🔹 10. Importing Encrypted Modules

  • Loads modules encrypted with a custom scheme.

🔍 How it works:

  • Decrypts an encoded module before execution.


Summary

Snippet
Description

1️⃣

Logs imports

2️⃣

Blocks specific imports

3️⃣

Dynamically creates modules

4️⃣

Imports from a ZIP file

5️⃣

Redirects imports

6️⃣

Makes modules read-only

7️⃣

Imports from a custom directory

8️⃣

Enforces naming conventions

9️⃣

Auto-reloads modules

🔟

Imports encrypted modules


Last updated