How to do relative imports in Python?
Everyone seems to want to tell you what you should be doing rather than just answering the question.
The problem is that you're running the module as '__main__' by passing the mod1.py as an argument to the interpreter.
From PEP 328:
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.
In Python 2.6, they're adding the ability to reference modules relative to the main module. PEP 366 describes the change.
Update: According to Nick Coghlan, the recommended alternative is to run the module inside the package using the -m switch.
Here is the solution which works for me:
I do the relative imports as
from ..sub2 import mod2and then, if I want to run
mod1.py then I go to the parent directory of
app and run the module using the python -m switch as
python -m app.sub1.mod1.
The real reason why this problem occurs with relative imports, is that relative imports works by taking the
__name__ property of the module. If the module is being directly run, then
__name__ is set to
__main__ and it doesn't contain any information about package structure. And, thats why python complains about the
relative import in non-package error.
So, by using the -m switch you provide the package structure information to python, through which it can resolve the relative imports successfully.
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)
Hope this helps someone who is fighting with relative imports problem, because going through PEP is really not fun.
main.pysetup.pyapp/ -> __init__.py package_a/ -> __init__.py module_a.py package_b/ -> __init__.py module_b.py
- You run
Alternatively 2 or 3 could use:
from app.package_a import module_a
That will work as long as you have
app in your PYTHONPATH.
main.py could be anywhere then.
So you write a
setup.py to copy (install) the whole app package and subpackages to the target system's python folders, and
main.py to target system's script folders.