What is the difference between an absolute import and a relative import, and when does a relative import fail?
Answer
An absolute import (`from mypackage.utils import helper`) spells out the full path from a top-level package, and works regardless of which module does the importing. A relative import (`from .utils import helper` or `from ..other import thing`) is expressed relative to the importing module's own position inside its package, using leading dots to mean "this package" or "a parent package". Relative imports only work inside a proper package (a module that Python knows has a `__package__`); running a script directly with `python module.py` instead of `python -m package.module` sets `__package__` to an empty context, and any relative import inside that script then fails with an `ImportError`.
Strong answer includes
- absolute imports spell out the full path from a top-level package
- relative imports use leading dots relative to the importing module's package position
- relative imports fail when a module is run directly instead of as part of a package
Practical example
Running
python mypackage/module.pydirectly makes any
from . import siblinginside `module.py` raise
ImportError: attempted relative import with no known parent package, while
python -m mypackage.moduleworks correctly.