Skip to content
๐Ÿ“˜ Absolute vs Relative Imports

๐Ÿ“˜ 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.randlist

is 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_list

The leading dot (.) means โ€œfrom the current package/module,โ€ and this is what Python formally defines as a relative import.


๐Ÿง  Summary Table

SyntaxTypeResolves From
import sort_utils.randlistAbsoluteFrom package root
from . import randlistRelativeFrom current moduleโ€™s package
import sorting.sort_utils.randlistAbsoluteFrom higher-level package root
Last updated on