204. Python’s Import Hooks
🔹 1. Basic Import Hook (Logging Imports)
Hooks into Python’s import system to log imports.
Copy
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.
Copy
🔍 How it works:
Blocks specific modules by raising an
ImportError.
🔹 3. Custom Module Loader
Loads a module dynamically at runtime.
Copy
🔍 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.
Copy
🔍 How it works:
zipimportallows loading Python modules from a ZIP file.
🔹 5. Redirecting Imports
Redirects an import to a different module.
Copy
🔍 How it works:
Any import of
mathgets replaced byrandom.
🔹 6. Creating a Read-Only Import Hook
Prevents modifications to imported modules.
Copy
🔍 How it works:
Makes module attributes immutable.
🔹 7. Importing from a Custom Directory
Loads modules from a specific directory outside
sys.path.
Copy
🔍 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.
Copy
🔍 How it works:
Prevents importing modules with uppercase names.
🔹 9. Auto-Reloading Modules on Import
Automatically reloads a module when imported.
Copy
🔍 How it works:
Forces a module to reload every time it’s imported.
🔹 10. Importing Encrypted Modules
Loads modules encrypted with a custom scheme.
Copy
🔍 How it works:
Decrypts an encoded module before execution.
Summary
SnippetDescription
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