title: Understanding A Chain of Imports in Python
body: <p>I know there are several similar questions, but I'm struggling to understand the error I'm getting and browsing the docs and similar questions hasn't helped yet.  If anything, the similar questions make me feel like what I'm doing is right.</p>
  
  <p>I have the following files:</p>
  
  <p><em><strong>src/main.py</em></strong></p>
  
  <pre><code>from pack import pack
  
  if __name__ == '__main__':
      pack.exec("Hello Universe!")
  </code></pre>
  
  <p><em><strong>src/pack/pack.py</em></strong></p>
  
  <pre><code>import util
  
  def exec(text):
      util.write(text)
  
  if __name__ == '__main__':
      exec("Hello World!")
  </code></pre>
  
  <p><em><strong>src/pack/util.py</em></strong></p>
  
  <pre><code>def write(text):
      print(text)
  </code></pre>
  
  <p>*<strong>src/pack/_<em>init</em>_.py*</strong></p>
  
  <pre><code>EMPTY FILE
  </code></pre>
  
  <hr>
  
  <p>When I run <code>python pack.py</code> from the <code>src/pack</code> directory, it works (prints "Hello World!").  However when I run <code>python main.py</code> from the <code>src</code> directory I get the following exception:</p>
  
  <pre><code>Traceback (most recent call last):
    File ".../src/main.py", line 1, in &lt;module&gt;
      from pack import pack
    File ".../src/pack/pack.py", line 1, in &lt;module&gt;
      import util
  ImportError: No module named util
  </code></pre>
  
  <hr>
  
  <p>If I change the import line in <code>pack.py</code> to <code>from . import util</code> as suggested, effectively the opposite occours.  <code>main.py</code> runs successfully, however now <code>pack.py</code> fails, raising:</p>
  
  <pre><code>Traceback (most recent call last):
    File ".../src/pack/pack.py", line 1, in &lt;module&gt;
      from . import util
  ValueError: Attempted relative import in non-package
  </code></pre>
  
  <hr>
  
  <p>I would have thought that imports are relative to the current location, and as such you ought to be able to construct a chain of imports like this.  It seems very odd to me that module is supposed to import a sibling file differently depending on where the program starts.</p>
  
  <p>Can someone explain why this error occurs in one way but not the other, and if there is some way to allow this file structure to run whether I want to run from <code>main.py</code> or <code>pack.py</code>?</p>