Python relative imports using setuptools with scripts
<p>I am transitioning to a package-based workflow for a project I've been working on. I want to be able to separate development and production environments and I think setuptools offers this possibility with some degree of ease.</p>

<p>I have a project structured as follows:</p>

<pre><code>modulename/
    setup.py
    modulename/
         file_a.py
         script.py
</code></pre>

<p>In script.py, I want to import file_a.py. Currently I do this by doing <code>import file_a</code>. </p>

<p>My setup.py looks like:</p>

<pre><code>from setuptools import setup, find_packages

setup(name='modulename',
  packages = find_packages(),
  package_dir = {'': '../modulename'},
  scripts = ['modulename/script.py'])
</code></pre>

<p>Currently, when I run <code>script.py</code> after doing <code>python setup.py install</code>, I get an error message:</p>

<p><code>SystemError: Parent module '' not loaded, cannot perform relative import</code></p>

<p>I have tried a variety of permutations of <code>package_dir = ...</code>, most notably <code>package_dir = {'': 'modulename'}</code>, but this throws another error on install, <code>error: package directory 'modulename/modulename' does not exist</code></p>

<p>I am not sure what I am doing wrong. The documentation online for setuptools is relatively poor in dealing with situations involving relative imports. Can someone point me in the right direction?</p>

<p>The problem is not related with <code>setuptools</code>. Using relative imports inside the module being executed as <code>__main__</code> does not work out of the box. There are workarounds / hacks, but the most common solutions seems to be moving the script out of the package or using absolute imports in the script file.</p>

<p>Take a look at <a href="http://stackoverflow.com/questions/16981921/relative-imports-in-python-3">Relative imports in Python 3</a> for the full story.</p>

python python-3.x import package