Python relative import weirdness

Question:

I have a file:

STARTDIR/module/submodule/config.py

I have another file:

STARDIR/utils/filesys/getAbsPath.py

Why does this line work, in config.py?

from ..utils.filesys import getAbsPath

It seems like .. refers to module, not STARTDIR. There isn’t any utils in module at all. In fact, doing

from .. import utils

yields

ImportError: cannot import name utils
Asked By: Claudiu

||

Answers:

This should work:

from ...utils.filesystem import getAbsPath

This is because:

  • from . import … imports from STARTDIR/module/submodule/
  • from .. import … imports from STARTDIR/module/
  • from ... import … imports from STARTDIR/
Answered By: David Wolever
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.