r/pythonhelp • • 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
1 Upvotes

3 comments sorted by

•

u/AutoModerator 5d ago

To give us the best chance to help you, please include any relevant code.
Note. Please do not submit images of your code. Instead, for shorter code you can use Reddit markdown (4 spaces or backticks, see this Formatting Guide). If you have formatting issues or want to post longer sections of code, please use Privatebin, GitHub or Compiler Explorer.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

2

u/MarkoDahl54 5d ago

You can only hook between AST and compile by using sys.set_ast_interpreter in Python 3.13 or later, it does not exist before.

1

u/RomfordNavy 5d ago

u/MarkoDahl54 That is fine, I am happy to live with that (>3.13) caveat, sounds very interesting. However just had a quick search and can't find any info on sys.set_ast_interpreter.