Modify 'import' command

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.

Why would you want to do this?