title: Relative imports in python 2.5
body: <p>I know that there are lots of questions about the same import issues in Python but it seems that nobody managed to provide a clear example of correct usage.</p>
  
  <p>Let's say that we have a package <code>mypackage</code> with two modules <code>foo</code> and <code>bar</code>. Inside <code>foo</code> we need to be able to access <code>bar</code>.</p>
  
  <p>Because we are still developing it, <code>mypackage</code> is not in <code>sys.path</code>. </p>
  
  <p>We want to be able to:</p>
  
  <ul>
  <li>import <code>mypackage.foo</code></li>
  <li>run <code>foo.py</code> as a script and execute the sample usage or tests from the <code>__main__</code> section.</li>
  <li>use Python 2.5</li>
  </ul>
  
  <p>How do we have to do the import in foo.py in order to be sure it will work in all these cases.</p>
  
  <pre><code># mypackage/__init__.py
  ...
  
  # mypackage/foo/__init__.py
  ...
  
  # mypackage/bar.py  
  def doBar()
      print("doBar")
  
  # mypackage/foo/foo.py
  import bar # fails with module not found
  import .bar #fails due to ValueError: Attempted relative import in non-package
  
  def doFoo():
      print(doBar())
  
  if __name__ == '__main__':
      doFoo()
  </code></pre>