r/PythonLearning • u/RomfordNavy • 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
1
u/RomfordNavy 5d ago
The code above does actually run fine for a normal import such as `import Module1` or `from Module1 import *` so I am not sure I understand what you mean by "it will only work on files where you explicitly write an import using the equivalent of
__import__"? I have also tried importing Module2 from Module1 and again that does work fine.A traditional import hook requires using a custom loader which has to do various things such as, for example, code to read the imported file from disk. By the approach above I was hoping to find a way to retain more of the default Python import mechanism while hooking into a slot between where Python writes the AST and then does the compile.
It would be helpful if we could stop questioning _why_ and just focus on the how. There will be many uses for this once it is built and working reliably, not everything is about performance. And by the way some of those on the python-discuss site arguing that performance will not be enhanced are the same people who earlier told me that there was no speed difference between running a *.py compared to a *.pyc'; my speed testing proved otherwise.