๐ Absolute vs Relative Imports
Motivation In Python, absolute imports refer to import paths that begin at the top-level package, regardless of the importing moduleโs location.
This often causes confusion when importing sibling modules.
๐ Common Misconception
โIf Iโm importing a sibling module, that must be a relative import.โ
Not true. Even if test.py and randlist.py live in the same folder, writing:
import sort_utils.randlistis still an absolute import, because it starts from the package root (sort_utils),
not from the current fileโs location.
โ True Relative Import Syntax
To use a relative import, youโd write:
from . import randlist
from .randlist import generate_listThe leading dot (.) means โfrom the current package/module,โ and this is what Python formally defines as a relative import.
๐ง Summary Table
| Syntax | Type | Resolves From |
|---|---|---|
import sort_utils.randlist | Absolute | From package root |
from . import randlist | Relative | From current moduleโs package |
import sorting.sort_utils.randlist | Absolute | From higher-level package root |
Last updated on