title: Importing Python modules from different levels of hierarchy
body: <p>Within the top level of my git repository, I have the following file structure:</p>
  
  <pre><code>miscellaneous Dockerfiles, readme, etc
  Code/
      training.py
      data/
          generate.py
          tasksets.py
  </code></pre>
  
  <p>Sometimes I want to import the <code>generate</code> module from within the <code>tasksets</code> module when I run the <code>tasksets</code> module as a script, so <code>tasksets</code> includes the following import:</p>
  
  <pre><code>import generate
  </code></pre>
  
  <p>Other times I want to import the <code>tasksets</code> module from within the <code>training</code> module, so <code>training</code> contains the following import:</p>
  
  <pre><code>import tasksets
  </code></pre>
  
  <p>However, this setup is giving me problems. <code>tasksets</code> can import <code>generate</code> fine when I run <code>tasksets</code> as a script, but throws an error if I import <code>tasksets</code> inside <code>training</code> when I run <code>training</code> as a script (I think because <code>training</code> can't find <code>generate</code> as a script within the default path). I've tried looking at all sorts of other StackOverflow questions and answers, using <code>__init__.py</code> files, relative imports, etc. Currently, my workaround is to use the following lines inside <code>tasksets</code>:</p>
  
  <pre><code>if __name__ == "__main__": import generate
  else: from data import generate
  </code></pre>
  
  <p>But this doesn't feel right (and my IDE don't like it neither). Please can someone explain how to use the right assortment of <code>__init__.py</code> files and import statements such that I can import <code>generate</code> when running <code>tasksets</code> as a script, and also import <code>tasksets</code> when running <code>training</code> as a script?</p>