title: How to import a submodule in Python? (without `exec`)
body: <p>I would like to import a submodule without knowing its name beforehand, </p>
  
  <pre class="lang-py prettyprint-override"><code>&gt;&gt;&gt; __import__("os.path")
  &lt;module 'os' from '/usr/lib/python3.3/os.py'&gt;
  </code></pre>
  
  <p>Doesn't work as you might expect, returning <code>os</code>, not <code>os.path</code>.</p>
  
  <p>I came up with this solution.</p>
  
  <pre><code>def import_submodule(mod, submod):
      ns = {}
      exec_str = "from %s import %s as submod" % (mod, submod)
      exec(exec_str, ns, ns)
      return ns["submod"]
  </code></pre>
  
  <p>This gives the result:</p>
  
  <pre><code>&gt;&gt;&gt; import_submodule("os", "path")
  &lt;module 'posixpath' from '/usr/lib/python3.3/posixpath.py'&gt;
  </code></pre>
  
  <p>However I would rather not use exec() because its rather bad practice and seems unnecessary when Pythons import mechanisms are available already through <code>__import__</code>, <code>imp</code> and <code>importlib</code> modules.</p>
  
  <p>Is there a way in Python3.x to do this kind of import though a function call, rather then using <code>exec()</code> ?</p>