Why ImportError only with from?
<p>I have two packages, <code>a</code> and <code>b</code>. They are in the same directory, and <code>b</code> is dependent on <code>a</code> (but NOT the other way around). When I run <code>from . import a</code> in <code>b\some_package.py</code>, I get <code>ImportError: cannot import name a</code>. When I run <code>import a</code> (from the appropriate directory), there is no error. Both packages have <code>__init__.py</code>s. <a href="http://stackoverflow.com/questions/6351805/cyclic-module-dependencies-and-relative-imports-in-python">This answer</a> explains why fairly well, but does not mention how to fix this. How can I  fix this?</p>

<p>File structure:</p>

<pre><code>parent_directory
    a
     __init__.py
     module_in_a.py
    b
     __init__.py
     module_in_b.py (this imports a)
</code></pre>

<p>Package relative imports cannot refer to modules outside of the package. This is impossible in the general sense because it assumes that module-relative paths are always the same as file system directories. But modules can be installed in many places and can be inside archives such as eggs.</p>

<p>If you install packages <code>a</code> and <code>b</code>, you don't have a problem. Python's <a href="https://virtualenv.pypa.io/en/stable/" rel="nofollow">virtualenv</a> can help with local installs that don't affect your system python modules. But you can also edit the <code>PYTHONPATH</code> environment variable to point to a place where you have installed <code>a</code> and <code>b</code> or you can change <code>sys.path</code> inside your program. For instance, </p>

<p>b/module_in_b.py</p>

<pre><code>import sys
import os

_my_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
if _my_path not in sys.path:
    sys.path.append(_my_path)
del _my_path

import a
</code></pre>

python python-2.7 import python-import