Does anyone know if it is possible to intercept the import statement somehow so that the source code could be automatically modified before it is saved as a compiled .pyc file? I think some might call this monkey-patching.
I do have an example of how to do this manually using a source_to_code PatchedLoader but no idea how to apply that to all imports automatically.
Yes, this is done using an import hook. There are many examples that you can find online. I wrote a library to help you do that Ideas: making it easier to extend Python’s syntax — ideas 0.3.14 documentation. There are others on Pypi. One that is less focused on code modification but does support all manners of patching is wrapt.
Thanks @aroberge that looks interesting, I will have a read and see if I can understand how it works.
Have to admit I was more thinking along the lines of modifying the Python install so that all code compiled by that is subject to my code_modify() function but I guess both ways would work.
You haven’t explained what you are trying to accomplish with source modification, and given past interactions here, I suspect you can’t be dissuaded from trying it.
I am certain Python provides a solution to your actual problem that will be simpler and easier than modifying source during import. If you explain what you need to do, and keep an open mind about doing things the natural Python way, we can help you with it.
Because if ‘compile’ time source code modification can be made to work reliably that opens-up all manner of possibilities for moving some runtime code into compile time.
That’s a bit like asking where you are intending to go to before learning to drive! Let’s see if I can get it working first and then find what functionality can be moved out to compile time afterwards.
Because of Python doesn’t have conditional compile so I usually have to write something like
if __debug__:
do_some_code_with_debugger
else:
do_some_code
Doing things this way not only cause larger bytecodes but also unnecessarily embed the debug clause in the released code. I haven’t find a proper solution for this situation yet.
Again, have you checked the disassembly? In optimized mode, if __debug__ and ... can never be true, and will be optimized out. Are you really sure you actually need a preprocessor?
Yes, both “condition is True” and “condition is False” are there. Am I misunderstand what you mean?
d:\Works\Python>py -3.8 -O
Python 3.8.10 (tags/v3.8.10:3d8993a, May 3 2021, 11:34:34) [MSC v.1928 32 bit (Intel)] on win32
Type “help”, “copyright”, “credits” or “license” for more information.
>>> __debug__
False
>>> def func():
... if __debug__ and condition:
... print("condition is True")
... else:
... print("condition is False")
...
>>> import dis
>>> dis.dis(func)
Since you’re NOT in debug mode, your if statement has to do real work. It’s functionally equivalent to if condition: though. How would a preprocessor help with that?
That’s not what that code says. He’s not in debug mode, so __debug__ is false, but the optimization does not get rid of the if (False and condition): print(...) clause, even though False and condition == False always.
I do wonder why you would need if __debug__ and condition: ... else: .... What kind of scenario is this? If it wasn’t specifically this, you could refactor as
We seem to be moving away from the original question and raising various irrelevant questions about why instead, can we please try and focus on the actual question rather than keep questioning why all the time.
So far I have this code, question is how can I retrieve the source code from mod in custom_import?
#Module1.py
print("in Module 1...")
#Main.py
import builtins
from inspect import getmembers
base_imp = builtins.__import__
def custom_import(*args, **kwargs):
mod = base_imp(*args, **kwargs)
for name, val in getmembers(mod):
print("in custom_import.", name, val)
return mod
builtins.__import__ = custom_import
print("in Main.py before import")
import Module1
print("in Main.py after import")