<p>Imagine this directory structure:</p>

<pre><code>app/
   __init__.py
   sub1/
      __init__.py
      mod1.py
   sub2/
      __init__.py
      mod2.py
</code></pre>

<p>I'm coding <code>mod1</code>, and I need to import something from <code>mod2</code>. How should I do it?  </p>

<p>I tried <code>from ..sub2 import mod2</code> but I'm getting an "Attempted relative import in non-package".</p>

<p>I googled around but found only "<code>sys.path</code> manipulation" hacks. Isn't there a clean way?  </p>

<hr>

<p>Edit: all my <code>__init__.py</code>'s are currently empty  </p>

<p>Edit2: I'm trying to do this because sub2 contains classes that are shared across sub packages (<code>sub1</code>, <code>subX</code>, etc.).</p>

<p>Edit3: The behaviour I'm looking for is the same as described in <a href="http://www.python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> (thanks John B)</p>

[{'answer_id': 73149, 'author': 'John B', 'author_id': 9597, 'author_profile': 'https://Stackoverflow.com/users/9597', 'pm_score': 10, 'selected': True, 'text': '<p>Everyone seems to want to tell you what you should be doing rather than just answering the question.</p>\n\n<p>The problem is that you\'re running the module as \'__main__\' by passing the mod1.py as an argument to the interpreter.</p>\n\n<p>From <a href="http://www.python.org/dev/peps/pep-0328/" rel="noreferrer">PEP 328</a>:</p>\n\n<blockquote>\n  <p>Relative imports use a module\'s __name__ attribute to determine that module\'s position in the package hierarchy. If the module\'s name does not contain any package information (e.g. it is set to \'__main__\') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.</p>\n</blockquote>\n\n<p>In Python 2.6, they\'re adding the ability to reference modules relative to the main module.  <a href="http://python.org/dev/peps/pep-0366/" rel="noreferrer">PEP 366</a> describes the change.</p>\n\n<p><strong>Update</strong>: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.</p>\n'}, {'answer_id': 465129, 'author': 'nosklo', 'author_id': 17160, 'author_profile': 'https://Stackoverflow.com/users/17160', 'pm_score': 7, 'selected': False, 'text': "<pre><code>main.py\nsetup.py\napp/ -&gt;\n    __init__.py\n    package_a/ -&gt;\n       __init__.py\n       module_a.py\n    package_b/ -&gt;\n       __init__.py\n       module_b.py\n</code></pre>\n\n<ol>\n<li>You run <code>python main.py</code>.</li>\n<li><code>main.py</code> does: <code>import app.package_a.module_a</code></li>\n<li><code>module_a.py</code> does <code>import app.package_b.module_b</code></li>\n</ol>\n\n<p>Alternatively 2 or 3 could use: <code>from app.package_a import module_a</code></p>\n\n<p>That will work as long as you have <code>app</code> in your PYTHONPATH. <code>main.py</code> could be anywhere then.</p>\n\n<p>So you write a <code>setup.py</code> to copy (install) the whole app package and subpackages to the target system's python folders, and <code>main.py</code> to target system's script folders.</p>\n"}, {'answer_id': 1083169, 'author': 'iElectric', 'author_id': 133235, 'author_profile': 'https://Stackoverflow.com/users/133235', 'pm_score': 5, 'selected': False, 'text': '<pre><code>def import_path(fullpath):\n    """ \n    Import a file with full path specification. Allows one to\n    import from anywhere, something __import__ does not do. \n    """\n    path, filename = os.path.split(fullpath)\n    filename, ext = os.path.splitext(filename)\n    sys.path.append(path)\n    module = __import__(filename)\n    reload(module) # Might be out of date\n    del sys.path[-1]\n    return module\n</code></pre>\n\n<p>I\'m using this snippet to import modules from paths, hope that helps</p>\n'}, {'answer_id': 6524846, 'author': 'jung rhew', 'author_id': 821632, 'author_profile': 'https://Stackoverflow.com/users/821632', 'pm_score': 2, 'selected': False, 'text': '<p>From <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports" rel="nofollow">Python doc</a>,</p>\n\n<blockquote>\n  <p>In Python 2.5, you can switch import‘s behaviour to absolute imports using a <code>from __future__ import absolute_import</code> directive. This absolute- import behaviour will become the default in a future version (probably Python 2.7). Once absolute imports are the default, <code>import string</code> will always find the standard library’s version. It’s suggested that users should begin using absolute imports as much as possible, so it’s preferable to begin writing <code>from pkg import string</code> in your code</p>\n</blockquote>\n'}, {'answer_id': 7541369, 'author': 'mossplix', 'author_id': 487623, 'author_profile': 'https://Stackoverflow.com/users/487623', 'pm_score': 3, 'selected': False, 'text': '<p>Take a look at <a href="http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports" rel="noreferrer">http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports</a>. You could do </p>\n\n<pre><code>from .mod1 import stuff\n</code></pre>\n'}, {'answer_id': 8195271, 'author': 'lesnik', 'author_id': 788775, 'author_profile': 'https://Stackoverflow.com/users/788775', 'pm_score': 6, 'selected': False, 'text': '<p>"Guido views running scripts within a package as an anti-pattern" (rejected\n<a href="http://www.python.org/dev/peps/pep-3122/">PEP-3122</a>)</p>\n\n<p>I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not.</p>\n'}, {'answer_id': 9541554, 'author': 'Garrett Berg', 'author_id': 674076, 'author_profile': 'https://Stackoverflow.com/users/674076', 'pm_score': 4, 'selected': False, 'text': '<p>This is unfortunately a sys.path hack, but it works quite well.</p>\n\n<p>I encountered this problem with another layer: I already had a module of the specified name, but it was the wrong module.</p>\n\n<p>what I wanted to do was the following (the module I was working from was module3):</p>\n\n<pre><code>mymodule\\\n   __init__.py\n   mymodule1\\\n      __init__.py\n      mymodule1_1\n   mymodule2\\\n      __init__.py\n      mymodule2_1\n\n\nimport mymodule.mymodule1.mymodule1_1  \n</code></pre>\n\n<p>Note that I have already installed mymodule, but in my installation I do not have "mymodule1"</p>\n\n<p>and I would get an ImportError because it was trying to import from my installed modules.</p>\n\n<p>I tried to do a sys.path.append, and that didn\'t work.  What did work was a <strong>sys.path.insert</strong></p>\n\n<pre><code>if __name__ == \'__main__\':\n    sys.path.insert(0, \'../..\')\n</code></pre>\n\n<p>So kind of a hack, but got it all to work!\nSo keep in mind, if you want your decision to <strong>override other paths</strong> then you need to use sys.path.insert(0, pathname) to get it to work!  This was a very frustrating sticking point for me, allot of people say to use the "append" function to sys.path, but that doesn\'t work if you already have a module defined (I find it very strange behavior)</p>\n'}, {'answer_id': 9748770, 'author': 'Andrew_1510', 'author_id': 451718, 'author_profile': 'https://Stackoverflow.com/users/451718', 'pm_score': 1, 'selected': False, 'text': '<p>I found it\'s more easy to set "PYTHONPATH" enviroment variable to the top folder:</p>\n\n<pre><code>bash$ export PYTHONPATH=/PATH/TO/APP\n</code></pre>\n\n<p>then:</p>\n\n<pre><code>import sub1.func1\n#...more import\n</code></pre>\n\n<p>of course, PYTHONPATH is "global", but it didn\'t raise trouble for me yet.</p>\n'}, {'answer_id': 12365065, 'author': 'Gabriel', 'author_id': 1621769, 'author_profile': 'https://Stackoverflow.com/users/1621769', 'pm_score': 1, 'selected': False, 'text': '<p>On top of what John B said, it seems like setting the <code>__package__</code> variable should help, instead of changing <code>__main__</code> which could screw up other things. But as far as I could test, it doesn\'t completely work as it should.</p>\n\n<p>I have the same problem and neither PEP 328 or 366 solve the problem completely, as both, by the end of the day, need the head of the package to be included in <code>sys.path</code>, as far as I could understand.</p>\n\n<p>I should also mention that I did not find how to format the string that should go into those variables. Is it <code>"package_head.subfolder.module_name"</code> or what? </p>\n'}, {'answer_id': 14189875, 'author': 'milkypostman', 'author_id': 154508, 'author_profile': 'https://Stackoverflow.com/users/154508', 'pm_score': 4, 'selected': False, 'text': '<p>Let me just put this here for my own reference. I know that it is not good Python code, but I needed a script for a project I was working on and I wanted to put the script in a <code>scripts</code> directory.</p>\n\n<pre><code>import os.path\nimport sys\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))\n</code></pre>\n'}, {'answer_id': 15458607, 'author': 'Pankaj', 'author_id': 382630, 'author_profile': 'https://Stackoverflow.com/users/382630', 'pm_score': 7, 'selected': False, 'text': "<p>Here is the solution which works for me:</p>\n\n<p>I do the relative imports as  <code>from ..sub2 import mod2</code>\nand then, if I want to run <code>mod1.py</code> then I go to the parent directory of <code>app</code> and run the module using the python -m switch as  <code>python -m app.sub1.mod1</code>.</p>\n\n<p>The real reason why this problem occurs with relative imports, is that relative imports works by taking the <code>__name__</code> property of the module. If the module is being directly run, then <code>__name__</code> is set to <code>__main__</code> and it doesn't contain any information about package structure. And, thats why python complains about the <code>relative import in non-package</code> error.  </p>\n\n<p>So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.</p>\n\n<p>I have encountered this problem many times while doing relative imports. And, after reading all the previous answers, I was still not able to figure out how to solve it, in a clean way, without needing to put boilerplate code in all files. (Though some of the comments were really helpful, thanks to @ncoghlan and @XiongChiamiov)</p>\n\n<p>Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.</p>\n"}, {'answer_id': 20449492, 'author': 'suhailvs', 'author_id': 2351696, 'author_profile': 'https://Stackoverflow.com/users/2351696', 'pm_score': 5, 'selected': False, 'text': "<p>explanation of <code>nosklo's</code> answer with examples</p>\n\n<p><em>note: all <code>__init__.py</code> files are empty.</em></p>\n\n<pre><code>main.py\napp/ -&gt;\n    __init__.py\n    package_a/ -&gt;\n       __init__.py\n       fun_a.py\n    package_b/ -&gt;\n       __init__.py\n       fun_b.py\n</code></pre>\n\n<h3>app/package_a/fun_a.py</h3>\n\n<pre><code>def print_a():\n    print 'This is a function in dir package_a'\n</code></pre>\n\n<h3>app/package_b/fun_b.py</h3>\n\n<pre><code>from app.package_a.fun_a import print_a\ndef print_b():\n    print 'This is a function in dir package_b'\n    print 'going to call a function in dir package_a'\n    print '-'*30\n    print_a()\n</code></pre>\n\n<h3>main.py</h3>\n\n<pre><code>from app.package_b import fun_b\nfun_b.print_b()\n</code></pre>\n\n<p>if you run <code>$ python main.py</code> it returns:</p>\n\n<pre><code>This is a function in dir package_b\ngoing to call a function in dir package_a\n------------------------------\nThis is a function in dir package_a\n</code></pre>\n\n<ul>\n<li>main.py does: <code>from app.package_b import fun_b</code> </li>\n<li>fun_b.py does <code>from app.package_a.fun_a import print_a</code></li>\n</ul>\n\n<p>so file in folder <code>package_b</code> used file in folder <code>package_a</code>, which is what you want. Right??</p>\n"}, {'answer_id': 30736316, 'author': 'LondonRob', 'author_id': 2071807, 'author_profile': 'https://Stackoverflow.com/users/2071807', 'pm_score': 3, 'selected': False, 'text': '<p>As @EvgeniSergeev says in the comments to the OP, you can import code from a <code>.py</code> file at an arbitrary location with:</p>\n\n<pre><code>import imp\n\nfoo = imp.load_source(\'module.name\', \'/path/to/file.py\')\nfoo.MyClass()\n</code></pre>\n\n<p>This is taken from <a href="https://stackoverflow.com/a/67692/2071807">this SO answer</a>.</p>\n'}, {'answer_id': 35338828, 'author': 'Роман Арсеньев', 'author_id': 5774201, 'author_profile': 'https://Stackoverflow.com/users/5774201', 'pm_score': 6, 'selected': False, 'text': '<p>This is solved 100%:</p>\n\n<ul>\n<li>app/\n\n<ul>\n<li>main.py</li>\n</ul></li>\n<li>settings/\n\n<ul>\n<li>local_setings.py</li>\n</ul></li>\n</ul>\n\n<p>Import settings/local_setting.py in app/main.py:</p>\n\n<p>main.py:</p>\n\n<pre><code>import sys\nsys.path.insert(0, "../settings")\n\n\ntry:\n    from local_settings import *\nexcept ImportError:\n    print(\'No Import\')\n</code></pre>\n'}, {'answer_id': 60846688, 'author': 'Giorgos Myrianthous', 'author_id': 7131757, 'author_profile': 'https://Stackoverflow.com/users/7131757', 'pm_score': 1, 'selected': False, 'text': '<p>You have to append the module’s path to <code>PYTHONPATH</code>: </p>\n\n<pre><code>export PYTHONPATH="${PYTHONPATH}:/path/to/your/module/"\n</code></pre>\n'}, {'answer_id': 70163621, 'author': 'Rohit Kumar J', 'author_id': 14376181, 'author_profile': 'https://Stackoverflow.com/users/14376181', 'pm_score': 0, 'selected': False, 'text': '<p>This method queries and auto populates the path:</p>\n<pre class="lang-py prettyprint-override"><code>import os\nimport inspect\ncurrentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\nparentdir = os.path.dirname(currentdir)\nos.sys.path.insert(1, parentdir)\n# print(&quot;currentdir = &quot;, currentdir)\n# print(&quot;parentdir=&quot;, parentdir)\n</code></pre>\n'}, {'answer_id': 71315540, 'author': 'F.M.F.', 'author_id': 4858818, 'author_profile': 'https://Stackoverflow.com/users/4858818', 'pm_score': 0, 'selected': False, 'text': '<p>A hacky way to do it is to append the current directory to the PATH at runtime as follows:</p>\n<pre><code>import pathlib   \nimport sys\nsys.path.append(pathlib.Path(__file__).parent.resolve())\nimport file_to_import  # the actual intended import\n</code></pre>\n<p>In contrast to another solution for this question this uses <code>pathlib</code> instead of <code>os.path</code>.</p>\n'}]
['https://Stackoverflow.com/questions/72852', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3497/']