Python Relative Imports
- Relative imports for intra-package imports are highly discouraged. Always use the absolute package path for all imports. Even now that PEP 328 is fully implemented in Python 2.5, its style of explicit relative imports is actively discouraged; absolute imports are more portable and usually more readable.
import package # searches sys.path only
implicit relative import:
explicit relative import:
from . import siblingmodule # use . or .. to explicitly signify relative path
In code snippets: use absolute imports
import package from package import module
Within modules: use explicit relative imports
from . import siblingmodule
Relative imports in non-packages
from . import module2
If the above line raises this error:
- Attempted relative import in non-package
You are attempting to import another python module from the same directory as your script. Apparently, you have just written that other file and that is a great piece of software that can be used a stand-alone module. Congrats.
The solution to fix this depends on where the error occurs.
If it is a script (thus has a shebang
#!/usr/bin/env python on top of the file), you should use an absolute import:
If it is another module, than you need to turn your scripts into a package. A package looks like the following file structure:
-+ package | +-- __init__.py | +-- module1.py | +-- module2.py
__init__.py file can be empty.
I do not recommend to change the