title: How to dynamically import `import x.y.z as z`in python
body: <p>To do</p>
  
  <pre><code>import itertools
  </code></pre>
  
  <p>dynamically, I can do the following</p>
  
  <pre><code>import importlib
  importlib.import_module('itertools')
  </code></pre>
  
  <p>But what should I do to do the following dynamically</p>
  
  <pre><code>import itertools as iters
  </code></pre>
  
  <p><strong>Problem Context:</strong></p>
  
  <p>I need to import a different version (0.10) of a module('pika' in my case), installed in a separate directory instead of default version(0.9). </p>
  
  <pre><code>Python 2.7.6 (default, Jun 22 2015, 17:58:13)
  [GCC 4.8.2] on linux2
  Type "help", "copyright", "credits" or "license" for more information.
  Welcome to Python !!
  &gt;&gt;&gt; import importlib
  &gt;&gt;&gt; import pika
  &gt;&gt;&gt; pika.__version__
  '0.9.14'
  &gt;&gt;&gt; import scale.lib.hypervisor.esx65.pika_3_5 as pika35
  &gt;&gt;&gt; pika35.__version__
  '0.10.0'
  &gt;&gt;&gt; importlib.import_module('scale.lib.hypervisor.esx65.pika_3_5')
  &lt;module 'scale.lib.hypervisor.esx65.pika_3_5' from 'scale/lib/hypervisor/esx65/pika_3_5/__init__.pyc'&gt;
  </code></pre>
  
  <p>As we can see regular imports are working fine. However when importing dynamically, importing relative to the location is causing issues. As per <a href="https://docs.python.org/3/library/importlib.html#importlib.import_module" rel="nofollow noreferrer">importlib.import_module documentaion </a>, following should work but it doesn't.</p>
  
  <pre><code>&gt;&gt;&gt; importlib.import_module('pika_3_5', 'scale.lib.hypervisor.esx65')
  Traceback (most recent call last):
    File "&lt;stdin&gt;", line 1, in &lt;module&gt;
    File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module
      __import__(name)
  ImportError: No module named pika_3_5
  </code></pre>
  
  <p>And when trying to import 'pika' from a relative path, which should fail as there is no module pika under the relative path, it is still importing it from default module. </p>
  
  <pre><code>&gt;&gt;&gt; importlib.import_module('pika', 'scale.lib.hypervisor.esx65.pika_3_5')
  &lt;module 'pika' from '/usr/local/lib/python2.7/dist-packages/pika/__init__.pyc'&gt;
  &gt;&gt;&gt;
  </code></pre>
  
  <p>What is it that I am missing ? I mainly want to do the following dynamically.</p>
  
  <pre><code>import scale.lib.hypervisor.esx65.pika_3_5 as pika
  </code></pre>