Relative import from within a 'Python Package'

Answered

Suppose the folowing project structure:
projext_dir/
    package/                (File->New->Python Package)
        A.py                   (File->New->Python File)
        B.py                   (File->New->Python File)

                     Now, let edit B.py and try the following

import A
...
Error: "No module named A"

                     on the other hand:

import package.A

No error.


Any clue why does the relative import within the Python Package does not work? Is it a bug?

 

1
1 comment

Hi Petr,

 

It's an example of somewhat confusing yet expected behavior, since in Python 3 you need to explicitly use dotted qualifiers in order to do relative imports: in this particular case "from . import A". What makes people really puzzled, though, is the fact that it works perfectly if you run B.py, but it happens because "package" directory is implicitly added in sys.path by interpreter so you don't actually perform any relative import at runtime. As we can't tell in advance statically which script you're going to use as an entry point to your program, you need then to explicitly mark "package" as a source root to inform us that it's available in sys.path during execution.

1

Please sign in to leave a comment.