Skip to content

apfel.impt.transform

This module provides a low-level hook mechanism to transform the source code of a package or module during its import. It must be imported before any other packages and modules that you want to hook.

Normally you would use adapters defined in the impt package, instead of directly using the low level register_transform_hook function.

API#

Classes

NameDescription
TransformPathFinderA subclass of :python importlib.machinery.PathFinder
TransformSourceFileLoaderA subclass of :python importlib.machinery.SourceFileLoader

Functions

NameDescription
register_transform_hookRegister a hook function to replace the source code of a module or package.

TransformPathFinderclass#

class TransformPathFinder(_frozen_importlib_external.PathFinder)

Bases: _frozen_importlib_external.PathFinder

A subclass of importlib.machinery.PathFinder that injects TransformSourceFileLoader to the import process.

find_specmethodclassmethod#

def find_spec(fullname: str, path: Sequence[str] | None = None, target: ModuleType | None = None) -> importlib.machinery.ModuleSpec | None

TransformSourceFileLoaderclass#

class TransformSourceFileLoader(fullname: str, path: str, *, hook: Sequence[Callable[[str], str]])

Bases: _frozen_importlib_external.SourceFileLoader

A subclass of importlib.machinery.SourceFileLoader that applies all registered hooks to the source code of a module or package during import.

hookattributeinstance attribute#

hook = hook

__init__method#

def __init__(fullname: str, path: str, *, hook: Sequence[Callable[[str], str]]) -> None

get_datamethod#

def get_data(path: str) -> bytes

set_datamethod#

def set_data(path, data, *, _mode: int = 438)

register_transform_hookfunction#

def register_transform_hook(name: str, hook: Callable[[str], str]) -> None

Register a hook function to replace the source code of a module or package.

Parameters

NameTypeDescription
namestrThe name of the module or package to hook.
hookCallable[[str], str]The hook function that takes the original source code as input and returns the transformed source code.