title: How can I create imports that always work?
body: <p>I am struggling a bit to set up a working structure in one of my projects. The problem is, that I have main package and a subpackage in a structure like this (I left out all unnecessary files):</p>
  
  <pre><code>code.py
  mypackage/__init__.py
  mypackage/work.py
  mypackage/utils.py
  </code></pre>
  
  <p>The utils.py has some utility code that is normally only used in the mypackage package.</p>
  
  <p>I normally have some test code each module file, that calls some methods of the current module and prints some things to quickcheck if everything is working correctly. This code is placed in a <code>if __name__ == "__main__"</code> block at the end of the file. So I include the utils.py directly via <code>import utils</code>. E.g mypackage/work.py looks like: </p>
  
  <pre><code>import utils
  
  def someMethod():
      pass
  
  if __name__ == "__main__":
      print(someMethod())
  </code></pre>
  
  <p>But now when I use this module in the parent package (e.g. code.py) and I import it like this</p>
  
  <pre><code>import mypackage.work
  </code></pre>
  
  <p>I get the following error:</p>
  
  <pre><code>ImportError: No module named 'utils'
  </code></pre>
  
  <p>After some research I found out, that this can be fixed by adding the <code>mypackage/</code> folder to the PYTHONPATH environment variable, but this feels strange for me. Isn't there any other way to fix this? I have heard about relative imports, but this is mentioned in the <a href="https://docs.python.org/3.5/tutorial/modules.html" rel="nofollow">python docs about modules</a> </p>
  
  <blockquote>
    <p>Note that relative imports are based on the name of the current module. Since the name of the main module is always "<strong>main</strong>", modules intended for use as the main module of a Python application must always use absolute imports.</p>
  </blockquote>
  
  <p>Any suggestions how I can have a <code>if __name__ == "__main__"</code> section in the submodule and also can use this file from the parent package without messing up the imports?</p>
  
  <p><strong>EDIT:</strong> If I use a relative import in <code>work.py</code> as suggested in a answer to import utils:</p>
  
  <pre><code>from . import utils
  </code></pre>
  
  <p>I get the following error:</p>
  
  <pre><code>SystemError: Parent module '' not loaded, cannot perform relative import
  </code></pre>