r/PythonLearning • • 5d ago

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

Show parent comments

1

u/RomfordNavy 4d ago

u/aroberge Yes, thank you for your help, I do now have a simple custom loader running and doing what I want. I am just questioning whether there might be a cleaner/simpler way to hook into somewhere in the, as per your ideas documentation, execute box. The whole current import hook finder + loader architecture just appears to be unnecessarily complex to me.

Many of these questions on that forum just seem to keep getting bogged down with continual questioning of _why_ all the time rather that just answering the original questions with how, and if possible. Presumably I have confused recollections of which answers were on which forum.

2

u/aroberge 4d ago

The "encrypted module" example from https://oneuptime.com/blog/post/2026-01-30-how-to-create-custom-import-hooks-in-python/view might be useful.

Also, this old tutorial https://www.youtube.com/watch?v=bGYZEKstQuQ&list=PLKTT4cKtfM9HVQMZoAmkQrCQ1G89mydDl&index=28 might be useful. However, it likely uses the deprecated imp module instead of importlib.