import hooks (custom module loaders) for pypy do not work
<p>I'm successfully able to create import hooks to load files directly from memory in python2.7.  The example I used was the accepted response to this question:</p>

<p><a href="http://stackoverflow.com/questions/14191900/pythonimport-module-from-memory">python:Import module from memory</a></p>

<p>However; when applying this code on pypy; i get an import error.  I have also tried other import hook examples that work with regular python but not with pypy, such as this:</p>

<p><a href="http://stackoverflow.com/questions/39135750/python-load-zip-with-modules-from-memory/39136473#39136473">python load zip with modules from memory</a></p>

<p>Does anyone know why import hooks do not work in pypy?  Is there something I am missing?</p>

<p>The problem is that in both of the examples you point to, <code>load_module()</code> does not add the loaded module to <code>sys.modules</code>.  Normally, it should do so (and then PyPy works like CPython).</p>

<p>If <code>load_module()</code> does not add the module to <code>sys.modules</code>, then every single <code>import a</code> will call <code>load_module()</code> again and return a new copy of the module.  For example, in the example from <a href="http://stackoverflow.com/questions/14191900/pythonimport-module-from-memory">python:Import module from memory</a>:</p>

<pre><code>import a as a1
import a as a2
print a1 is a2   # False!
a1.foo = "foo"
print a2.foo     # AttributeError
</code></pre>

<p>This is documented in <a href="https://www.python.org/dev/peps/pep-0302/#id27" rel="nofollow">https://www.python.org/dev/peps/pep-0302/#id27</a>.  The <code>load_module()</code> method is responsible for doing more checks than these simple examples show.  In particular, note this line (emphasis in the original):</p>

<blockquote>
  <p>Note that the module object <em>must</em> be in sys.modules before the loader executes the module code.</p>
</blockquote>

<p>So, the fact that PyPy behaves differently than CPython in this case could be understood as a behavior difference that follows from code that fails to respect the docs.</p>

<p>But anyway, my opinion is that it should be fixed.  I've created an issue at <a href="https://bitbucket.org/pypy/pypy/issues/2382/sysmeta_path-not-working-like-cpythons" rel="nofollow">https://bitbucket.org/pypy/pypy/issues/2382/sysmeta_path-not-working-like-cpythons</a>.</p>

python pypy