Python: importing a sub-package module from both the sub-package and the main package
<p>Here we go with my first ever stackoverflow quesion. I did search for an answer, but couldn't find a clear one. Here's the situation. I've got a structure like this:</p>

<pre><code>myapp
    package/
         __init.py__
         main.py
         mod1.py
         mod2.py
</code></pre>

<p>Now, in this scenario, from main.py I am importing mod1.py, which also needs to be imported by mod2.py. Everything works fine, my imports look like this:</p>

<p>main.py:</p>

<pre><code>from mod1 import Class1
</code></pre>

<p>mod2.py:</p>

<pre><code>from mod1 import Class1
</code></pre>

<p>However, I need to move my main.py to the main folder structure, like this:</p>

<pre><code>myapp
    main.py
    package/
         __init.py__
         mod1.py
         mod2.py
</code></pre>

<p>And now what happens is that of course I need to change the way I import mod1 inside main.py:</p>

<pre><code>from package.mod1 import Class1
</code></pre>

<p>However, what also happens is that in order not to get an "ImportError: No module named 'mod1'", I have make the same type of change inside mod2.py:</p>

<pre><code>from package.mod1 import Class1
</code></pre>

<p>Why is that? mod2 is in the same folder/pakcage as mod1, so why - upon modifying main.py - am I expected to modify my import inside mod2?</p>

<p>The reason this is happening is because how python looks for modules and packages when you run a python script as the <code>__main__</code> script.</p>

<p>When you run <code>python main.py</code>, python will add the parent directory of <code>main.py</code> to the pythonpath, meaning packages and modules within the directory will be importable.  When you moved main.py, you changed the directory that was added to the pythonpath.</p>

<p>Generally, you don't want to rely on this mechanism for importing your modules, because it doesn't allow you to move your script and your package and modules are <em>only</em> importable when running that main script.  What you should do is make sure your <code>package</code> is installed into a directory that is already in the pythonpath.  There are several ways of doing this, but the most common is to create a <code>setup.py</code> script and actually <a href="https://packaging.python.org/distributing/" rel="nofollow">install your python package</a> for the python installation on your computer.</p>

python import