[ad_1]
 
Now that we understand how Pythonâs import system works, letâs build our own Finder and Loader to intercept imports and modify module behavior!
đľď¸ Creating a Finder
A Finder is responsible for locating modules. To create one, we define a class with a find_spec method:
- Returns a
ModuleSpecobject if it finds the module. - Returns
Noneif it doesnât find it, it will allow Python to move to the next import hook. 
Letâs implement a custom finder that intercepts imports of a specific module:
import importlib.abc
import importlib.util
from importlib.machinery import PathFinderclass CustomFinder(importlib.abc.MetaPathFinder):
def __init__(self, intercepted_module) -> None:
self.intercepted_module = intercepted_module
self.finder = PathFinder()
super().__init__()
def find_spec(self, fullname, path, target=None):
if not fullname.startswith(self.intercepted_module): 
return None  # Move to the next finder
print(f"Intercepting import: {fullname}")
spec = self.finder.find_spec(fullname, path, target)
if spec is None:
return None
spec.loader = CustomLoader()
return spec
 Now, any attempt to import a module matching intercepted_module will be intercepted by our custom Finder.
âĄCreating a Loader
A Loader is responsible for executing the module code. Our Finder referenced a CustomLoader , so letâs create that next:
To implement a Loader, we need:
create_module(self, spec): Instantiates a new module object.exec_module(self, module): Executes the moduleâs code.
Hereâs our custom loader in action:
class CustomLoader(importlib.abc.Loader):
def create_module(self, spec):
return None  # Use default module creationdef exec_module(self, module):
print(f"Executing module: {module.__name__}")
# Read the module's source code
with open(module.__spec__.origin, "r") as f:
source_code = f.read()
# Modify the source code (add logging)
modified_code = 'print("Custom Hook: Module Loaded!")\n' + source_code
# Execute the modified code within the module's namespace
exec(modified_code, module.__dict__)
 Now, when a module is imported, our loader:
- Reads its source code.
 - Modifies it (in this case, adding a log message).
 - Executes the modified code.
 
đ ď¸Installing the Custom Hook
We have our Finder and Loader, but Python wonât use them until we register them in sys.meta_path :
import sys# Register the custom finder to intercept 'json' imports
sys.meta_path.insert(0, CustomFinder("json"))
# Import the target module (should trigger the hook)
import json
 đOutput
When you import json , hereâs what happens:
Intercepting import: json
Executing module: json
Custom Hook: Module Loaded!
Intercepting import: json.decoder
Executing module: json.decoder
Custom Hook: Module Loaded!
Intercepting import: json.scanner
Executing module: json.scanner
Custom Hook: Module Loaded!
Intercepting import: json.encoder
Executing module: json.encoder
Custom Hook: Module Loaded! Since json has submodules ( decoder , scanner , encoder ), our Finder intercepts all of them too !
Our CustomFinder hooks into the import system, intercepting modules before the default importers get a chance.
Source link 
 
 #Extension #Python
 
 [ad_2]
 








