Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question

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 example
python mypackage/module.py

directly makes any

Python example
from . import sibling

inside `module.py` raise

Python example
ImportError: attempted relative import with no known parent package

, while

Python example
python -m mypackage.module

works correctly.

#imports#packages#gotchas

Sources

The import systemPython Software Foundation · Module resolution, sys.path, packages and import caching