title: relative paths for modules in python
body: <p>I've attempted a few different techniques trying to do something that to me seems doable but I guess I am missing some gotchas about python (using 2.7 but would like this to work also for 3.* if possible). </p>
  
  <p>I am not sure about terminology like package or module, but to me the following seems quite a "simple" doable scenario.</p>
  
  <p>This is the directory structure:</p>
  
  <pre><code>.
  ├── job
  │   └── the_script.py
  └── modules
      ├── __init__.py
      └── print_module.py
  </code></pre>
  
  <p>The content of <code>the_script.py</code>:</p>
  
  <pre><code># this does not work
  import importlib
  print_module = importlib.import_module('.print_module', '..modules')
  
  # this also does not work
  from ..modules import print_module
  
  print_module.do_stuff()
  </code></pre>
  
  <p>The content of <code>print_module</code>:</p>
  
  <pre><code>def do_stuff():
      print("This should be in stdout")
  </code></pre>
  
  <p>I would like to run all this "relative paths" stuff as:</p>
  
  <pre><code>/job$ python2 the_script.py
  </code></pre>
  
  <p>But the <code>importlib.import_module</code> gives various errors:</p>
  
  <ul>
  <li>if I just use 1 input parameter <code>..modules.print_module</code>, then I get: <code>TypeError("relative imports require the 'package' argument")</code></li>
  <li>if I use 2 input parameters (as in the example above), then I get: <code>ValueError: Empty module name</code></li>
  </ul>
  
  <p>On the other hand using the <code>from ..modules</code> syntax I get: <code>ValueError: Attempted relative import in non-package</code>.</p>
  
  <p>I think the <code>__init__.py</code> empty file should be enough to qualify that code as "packages" (or modules? not sure about the terminology), but it seems there's something I am missing about how to manage relative paths.</p>
  
  <p>I read that in the past people was hacking this using the <code>path</code> and other functions from <code>import os</code> and <code>import sys</code>, but according to the official docs (python 2.7 and 3.*) this should not be needed anymore.</p>
  
  <p>What am I doing wrong and how could I achieve the result of printing the content <code>modules/print_module.do_stuff</code> calling it from a script in the "relative directory" <code>job/</code>?</p>