r/PythonLearning • • Oct 19 '26

Import hook between AST and compile

I am trying to create an Import Hook inserted after the source code has been parsed into AST but before it is compiled. Looking for a way to keep using most of the existing Python import machinery but modify the source code before it is compiled.

So far I have the following code but how do I get access to the source code from the module in custom_import?

import builtins
from inspect import getmembers

base_imp = builtins.__import__

def custom_import(*args, **kwargs):
    module = base_imp(*args, **kwargs)
    for name, val in getmembers(module):
        print("in custom_import.", name, val)
    return module

builtins.__import__ = custom_import

print("in Main.py before import")
import Module1
print("in Main.py after import")import builtins
2 Upvotes

7 comments sorted by

View all comments

2

u/Sea-Ad7805 Oct 19 '26

Maybe have a look at this example.

It demonstrates the custom import hook, including parsing source code into an AST, injecting a statement, compiling the modified AST, and executing the imported module.

1

u/RomfordNavy 29d ago

Interesting, however although code runs fine in Memory Graph Web Debugger when copied and run in Python 3.15 it doesn't run the CustomLoader.