In another blog, we discussed how to use relative import path as a better practice.
However sometimes if we want to use absolute import path when developing packages, here is how it can be done.
To ensure that absolute imports work correctly in a normal Python package, follow these steps:
- Organize your package structure:
Make sure your package has a well-organized structure with __init__.py
files in each directory. This allows Python to recognize the directories as packages. For example:
mypackage/ |
- Set up your
PYTHONPATH
:
Ensure that the top-level directory containing your package is included in the PYTHONPATH
environment variable. This allows Python to find your package when using absolute imports.
You can add the top-level directory to the PYTHONPATH
by running the following command in your terminal:
export PYTHONPATH="/path/to/top-level-directory:$PYTHONPATH" |
Replace /path/to/top-level-directory
with the actual path to the directory containing your package.
Or in your python code, simply add system path like this:
import sys |
- Use absolute imports:
Now you can use absolute imports in your package files. For example, in module1.py
, you can import module2.py
using an absolute import:
from mypackage.subpackage2 import module2 |
By following these steps, you can ensure that absolute imports work correctly in your Python package, even for files in subdirectories.