Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Absolute and Relative Imports in Python
In Python, when you need to access code from another file or package, you use import statements. There are two approaches − absolute imports (full path from the project root) and relative imports (path relative to the current file).
How Python Resolves Imports
When Python encounters an import statement, it searches in this order −
-
Module cache − Checks
sys.modulesfor previously imported modules. - Built-in modules − Searches Python's standard library.
-
sys.path − Searches directories in
sys.path(current directory first). - If not found anywhere, raises
ModuleNotFoundError.
Import Order Convention
Import statements should be at the top of the file in this order −
# 1. Standard library import os import sys # 2. Third-party packages import requests import numpy # 3. Local application imports from mypackage import mymodule
Project Structure
Consider this project layout for the examples below −
my_project/ ??? packageA/ ? ??? __init__.py ? ??? moduleA1.py ? ??? moduleA2.py # contains myfunc() ??? packageB/ ? ??? __init__.py ? ??? moduleB1.py ??? main.py
Absolute Import
Specifies the full path from the project root using dots as separators ?
# In main.py ? import myfunc from packageA/moduleA2.py from packageA.moduleA2 import myfunc # Other absolute import styles import packageA.moduleA1 from packageA import moduleA2
The path starts from the project root and traces down to the target module. A dot (.) replaces the slash (/) in the directory path.
Relative Import
Specifies the path relative to the current file's location. A single dot (.) means the current package, two dots (..) means one level up ?
# In packageB/moduleB1.py ? import moduleA1 from packageA from ..packageA import moduleA1 # In packageA/moduleA1.py ? import from same package from . import moduleA2 from .moduleA2 import myfunc
The .. in the first example means: go up one directory from packageB/ to my_project/, then into packageA/.
Comparison
| Feature | Absolute Import | Relative Import |
|---|---|---|
| Syntax | from packageA.moduleA2 import myfunc |
from .moduleA2 import myfunc |
| Readability | Clear − shows full path | Shorter but less obvious |
| Refactoring | Must update if project structure changes | Survives project relocation |
| Length | Can be lengthy for deep packages | Short |
| Recommended | Yes (PEP 8 preferred) | Use within the same package |
Conclusion
Use absolute imports as the default (clearer, PEP 8 recommended). Use relative imports within the same package for shorter paths that survive project relocation. Always place import statements at the top of the file in the order: standard library, third-party, then local.
