Import vs import on circular import?
<p>I read <a href="http://stackoverflow.com/questions/7336802/how-to-avoid-circular-imports-in-python/37126790#37126790">this post</a> about how to prevent circular import in python. I don't understand a claim in the post: </p>

<pre><code>import package.a # Absolute import and 
import a # Implicit relative import (deprecated, py2 only)
</code></pre>

<p>can avoid circular import but</p>

<pre><code>from ... import ...
#or
import ... as .. 
</code></pre>

<p>can't (on python 2.x). </p>

<p>Does anyone know the reason behind this?</p>

<p>After some search, I figure out the answer myself.</p>

<p>Essentially, circular import is a problem for <code>from â¦ import â¦</code> because it returns the imported module only after the module code is executed.</p>

<p>To illustrate, assume we have import a in b.py and import b in a.py. For <code>import a</code> and <code>import b</code>, I simply look up sys.modules to find a/b, just put a new module in and return.</p>

<p>On the other hand, <code>from a import c</code> in b.py has code like this (pseudo python, similar for <code>from b import d</code> in a.py)</p>

<pre><code>if 'a' not in sys.modules:
    sys.modules[a] = (A new empty module object)
    run every line of code in a.py
    add the module a to its parent's namespace
return module 'a'
</code></pre>

<p>we start from a.py, put an empty module for b to sys.modules and start executing b.py and put a in sys.modules and executing a.py. Next it hits <code>from b import d</code> again and find the b in sys.modules but it's empty, throws error: no attribute d.</p>

<p>PS1: the referred post is wrong. <code>import ... as ...</code> is good for circular import.</p>

<p>PS2: <code>from a import c</code> is the same to import a.c in python 3 </p>

python python-2.7 import