python3 explicit relative importing error

102 Views Asked by At

I'm staring to package my python code. My package structure is:

mypackage/
    __init__.py
    /subpackage
        __init__.py
        module1.py
        module2.py

In my module2, if I use absolute importing like:

from mypackage.subpackage import module1

this will work.

However, If I use explicit importing like:

from . import module1

This gives me

ImportError: attempted relative import with no known parent package


I've googling about this and find out that implicit relative import is not good. But my import is explicit and it gives me such an error message. Can somebody help me understand why? Thanks

1

There are 1 best solutions below

1
On

Relative import only works from inside a package. If you had mypackage as a requirement to your actual executable code (a pure library) and used explicit relative imports, it would be fine. However if you're trying to run module2 directly, your code says

Find the package that __main__ is in, find its parent, and find ITS child named module1

This is obviously nonsense, since __main__ has no parent (by definition)