Python -- import the package in a module that is inside the same package
<p>I have a project structure something like this...</p>

<pre><code>/some_app
    build/
    README
    out.py
    some_app/
        __init__.py
        mod1.py
        mod2.py
</code></pre>

<p>Now I want to import <code>some_app</code> package into <code>mod2</code>, without messing with <code>sys.path</code> trickery. What I simply did is...</p>

<pre><code># mod2.py
import some_app
</code></pre>

<p>Now when I run the mod2.py from the command line</p>

<pre><code>some_app $ python mod2.py
</code></pre>

<p>it throws error <code>ImportError: No module named some_app</code></p>

<p>BUT, inside the <code>out.py</code> file, when I do </p>

<pre><code># out.py
import some_app.mod2
</code></pre>

<p>and then do</p>

<pre><code>some_app $ python out.py
</code></pre>

<p>it runs perfectly.</p>

<p>Hence, what is happening is this. I load a package in a module that is within the same package, and then run that module as the <code>__main__</code> file -- and it doesn't work. Next, I load the same module (the one that I ran as <code>__main__</code>) inside another module, and then run that another module as <code>__main__</code> -- and it works.</p>

<p>Can someone please elaborate on what's going on here?</p>

<p><strong>UPDATE</strong></p>

<p>I understand that there is no straightforward reason for doing this -- because I could have directly imported any modules inside the <code>some_app</code> package. The reason I am trying this is because, in the Django project, this is what they're doing. See <a href="https://github.com/django/django/blob/master/django/http/multipartparser.py" rel="nofollow">this file for example</a></p>

<p>In every module, all the non-standard imports start with <code>django.</code>. So I wondered why and how they are doing that.</p>

<p><strong>UPDATE 2</strong></p>

<p>Relevant links</p>

<ul>
<li><a href="http://stackoverflow.com/questions/72852/how-to-do-relative-imports-in-python">How to do relative imports in Python?</a></li>
<li><a href="http://stackoverflow.com/questions/436497/python-import-the-containing-package">Python: import the containing package</a></li>
</ul>
