title: Python: Importing arbitrarily named source files using importlib
body: <p>I use the <code>imp</code> module to import Python modules from source, given the absolute filename. I.e.</p>
  
  <pre><code>import imp
  my_module = imp.load_source('my_module', '/paht/to/my_module')
  </code></pre>
  
  <p>Here, <code>/paht/to/my_module</code> is the full path to a file containing Python source code, even though it does not have a <code>.py</code> extension.</p>
  
  <p>When doing <code>import imp</code> in Python 3.7, the following deprecation warning is shown:</p>
  
  <blockquote>
    <p>DeprecationWarning: the imp module is deprecated in favour of importlib; see the module's documentation for alternative uses</p>
  </blockquote>
  
  <p>I am thus in search for an <code>importlib</code> replacement of the <code>imp.load_source</code> function. From the <a href="https://docs.python.org/3/library/importlib.html#importing-a-source-file-directly" rel="nofollow noreferrer">docs</a>, I have the following:</p>
  
  <pre><code>import importlib.util
  spec = importlib.util.spec_from_file_location('my_module', '/paht/to/my_module')
  module = importlib.util.module_from_spec(spec)
  spec.loader.exec_module(module)
  </code></pre>
  
  <p>This does not work when the filename has no extension, as in my case. I guess it fails because none of the implemented "finders" recognize the file as a Python source file. However, I do not really need all the complicated machinery provided by these finders, as I know for sure the absolute path to the file already. I simply want it imported.</p>
  
  <p>A simple hack would be to just read in the source as text and execute it manually in its own namespace, something like</p>
  
  <pre><code>my_module = {} 
  exec(open('/paht/to/my_module').read(), my_module)
  </code></pre>
  
  <p>(with this, names defined in <code>my_module</code> is available through <code>my_module['name']</code> rather than <code>my_module.name</code>, but you get the idea). I would like to know the proper way of doing this, using <code>importlib</code>.</p>