[Python] How to implement an import hook that can modify the source code on the fly using...

Discussão em 'Python' iniciado por Stack, Abril 20, 2025.

  1. Stack

    Stack Membro Participativo

    Using the deprecated module imp, I can write a custom import hook that modifies the source code of a module on the fly, prior to importation/execution by Python. Given the source code as a string named source below, the essential code needed to create a module is the following:

    module = imp.new_module(name)
    sys.modules[name] = module
    exec(source, module.__dict__)


    Since imp is deprecated, I would like to do something similar with importlib. [EDIT: there are other imp methods that need to be replaced to build a custom import hook - so the answer I am looking for is not simply to replace the above code.]

    However, I have not been able to figure out how to do this. The importlib documentation has a function to create modules from "specs" which, as far as I can tell, are objects that include their own loaders with no obvious way to redefine them so as to be able to create a module from a string.

    I have created a minimal example to demonstrate this; see the README file for details.

    Continue reading...

Compartilhe esta Página