Python Relative & Absolute Import
In Python, there are two types of imports: relative and absolute
Relative imports allow you to import Python modules that are located in a different directory from the current Python script. Relative imports are specified using the . notation. For example, if you have the following file structure:
project/ main.py module1/ __init__.py script1.py
You can import
script1.py from main.py using a relative import:
# main.py from .module1 import script1
The . notation indicates that script1.py is located in a subdirectory of the current directory. The number of dots used in the import statement indicates the level of the subdirectory.
For example, if main.py and module1 are located in the same directory and you want to import script1.py from main.py, you can use a single dot:
# main.py from . import script1
If main.py is located in a subdirectory of module1, you can use two dots to specify the parent directory:
# main.py from .. import script1
Absolute imports, on the other hand, allow you to import Python modules from the root directory of your project. Absolute imports specify the full path to a module, starting from the root directory of your project. For example, for the same file structure as above, you can import script1.py from main.py using an absolute import:
# main.py from module1 import script1
Most of the common pitfalls involve statements with relative imports:
- Importing a module from a different directory using a relative import may not work if the module is not located in a package (i.e., a directory with an init.py file).
- Using a relative import to import a module from a different directory may not work if the current Python script is located outside of the project directory.
- Importing a module using an absolute import may not work if the module is located in a different Python path (e.g., a different virtual environment or a system-wide Python installation).
- If you use a relative import and then move your Python script to a different directory, the import may break because the relative path to the module will be different.