title: How can I write the python import statements, such that the file works from both inside and outside its package?
body: <p>Here's a file structure I'm working with:</p>
  <pre class="lang-none prettyprint-override"><code>package_example/
    main.py
    the_package/
      __init__.py
      pkg_file_1.py
      pkg_file_2.py
  </code></pre>
  <p>Here are the files:</p>
  <pre class="lang-py prettyprint-override"><code># main.py
  from the_package.pkg_file_1 import foo_1
  
  
  def main():
      foo_1()
  
  
  if __name__ == &quot;__main__&quot;:
      main()
  </code></pre>
  <pre class="lang-py prettyprint-override"><code># pkg_file_1.py
  from the_package import pkg_file_2
  
  
  def foo_1():
      print(&quot;this is the second version, foo_1&quot;)
      pkg_file_2.foo_2()
  
  
  if __name__ == &quot;__main__&quot;:
      foo_1()
  </code></pre>
  <pre class="lang-py prettyprint-override"><code># pkg_file_2.py
  
  def foo_2():
      print(&quot;this is foo_2&quot;)
  
  </code></pre>
  <p>If I run <code>main.py</code>, everything works fine.</p>
  <p>But if I run <code>pkg_file_1.py</code>, I get:</p>
  <pre><code>Traceback (most recent call last):
    File &quot;the_package/pkg_file_1.py&quot;, line 1, in &lt;module&gt;
      from the_package import pkg_file_2
  ModuleNotFoundError: No module named 'the_package'
  </code></pre>
  <p>Obviously in this simplified example, it doesn't matter, since <code>main.py</code> and <code>pkg_file_1.py</code> run the same code.</p>
  <p>But practically, I have test scripts baked into my package structure, so I can test the code in my new environment and data. But I'm scratching my head on how I'm supposed write import statements such that I don't get a <code>ModuleNotFoundError</code> from both inside or outside the package.</p>
  <p>Edit: From pavel's suggest I tried changing <code>pkg_file_1.py</code> to:</p>
  <pre class="lang-py prettyprint-override"><code>from ..the_package import pkg_file_2
  
  
  def foo_1():
      print(&quot;this is the second version, foo_1&quot;)
      pkg_file_2.foo_2()
  
  
  if __name__ == &quot;__main__&quot;:
      foo_1()
  
  </code></pre>
  <p>But running that same file gives:</p>
  <pre><code>Traceback (most recent call last):
    File &quot;the_package/pkg_file_1.py&quot;, line 1, in &lt;module&gt;
      from ..the_package import pkg_file_2
  ImportError: attempted relative import with no known parent package
  </code></pre>