How to use absolute import path in python package


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:

  1. 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/
__init__.py
main.py
subpackage1/
__init__.py
module1.py
subpackage2/
__init__.py
module2.py
  1. 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
sys.path.append('/path/to/top-level-directory')

  1. 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.


Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC