title: How to replace usages of deprecated imp.load_dynamic?
body: <p>The <code>imp</code> module is deprecated (since version 3.4), however some parts of the infrastructure (e.g. <a href="https://github.com/cython/cython/blob/7f26ba41ced0a95e2aef6ed608302fe743d836dd/pyximport/pyximport.py#L216" rel="noreferrer"><code>pyximport</code></a>) still use <a href="https://docs.python.org/3.0/library/imp.html#imp.load_dynamic" rel="noreferrer"><code>imp.load_dynamic</code></a>, which leads to deprecation-warnings with newer Python versions.</p>
  <p>Internally, <code>imp.load_dynamic</code> uses <a href="https://github.com/python/cpython/blob/e471e72977c83664f13d041c78549140c86c92de/Lib/imp.py#L330-L342" rel="noreferrer"><code>importlib</code>-machinery</a>:</p>
  <pre><code>from importlib._bootstrap import _load
  def load_dynamic(name, path, file=None):
      &quot;&quot;&quot;**DEPRECATED**
      Load an extension module.
      &quot;&quot;&quot;
      import importlib.machinery
      loader = importlib.machinery.ExtensionFileLoader(name, path)
  
      # Issue #24748: Skip the sys.modules check in _load_module_shim;
      # always load new extension
      spec = importlib.machinery.ModuleSpec(
          name=name, loader=loader, origin=path)
      return _load(spec)
  </code></pre>
  <p>But it feels silly to duplicate this code (which <a href="https://bugs.python.org/issue24748" rel="noreferrer">at least once</a> had to be improved) for all kind of projects.</p>
  <p><code>importlib</code>'s documentation <a href="https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly" rel="noreferrer">proposes</a> the following:</p>
  <pre><code>import importlib.util
  import sys
  def alternative_load_dynamic(name, path, file=None):
      spec = importlib.util.spec_from_file_location(name, path)
      module = importlib.util.module_from_spec(spec)
      sys.modules[name] = module
      spec.loader.exec_module(module)
      return sys.modules[name]
  </code></pre>
  <p>While it has the advantage of not using the private API compared to the first implementation (i.e. <code>_load</code>) and gets the behavior at the core of <a href="https://bugs.python.org/issue24748" rel="noreferrer">issue #24748</a> right, it is not a drop-in replacement for <code>imp.load_dynamic</code>:</p>
  <ul>
  <li>this alternative can more: it can also load pure python modules (<code>*.py</code> or <code>*.pyc</code>).</li>
  <li>this alternative can less: it can only load dynamic modules with ending <code>*.so</code> (or <code>*.pyd</code> on Windows), but not for example <code>foo.my_ending</code>.</li>
  </ul>
  <p>What are other options to replace <code>imp.load_dynamic</code>?</p>