title: How to implement an import hook that can modify the source code on the fly using importlib?
body: <p>Using the deprecated module <code>imp</code>, 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 <code>source</code> below, the essential code needed to create a module is the following:</p>
  
  <pre><code>module = imp.new_module(name)
  sys.modules[name] = module
  exec(source, module.__dict__)
  </code></pre>
  
  <p>Since <code>imp</code> is deprecated, I would like to do something similar with <code>importlib</code>. [EDIT: there are other <code>imp</code> 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.] </p>
  
  <p>However, I have not been able to figure out how to do this. The <a href="https://docs.python.org/3/library/importlib.html" rel="noreferrer">importlib documentation</a> has a <a href="https://docs.python.org/3/library/importlib.html#importlib.util.module_from_spec" rel="noreferrer">function to create modules from "specs"</a> 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. </p>
  
  <p>I have created a <a href="https://github.com/aroberge/splore/tree/master/import_hook" rel="noreferrer">minimal example</a> to demonstrates this; see the readme file for details.</p>