How to avoid "Attempted relative import with no known parent package" with this simple package?

Viewed 7355

Inside packagetest/, I have these four files:

  • __init__.py:

    class TestError(Exception):
        pass
    
  • __main__.py:

    from . import TestError
    from .abc import defgh
    from .ijk.lmn import opq
    
  • abc/__init__.py:

    def defgh():
        pass
    
  • ijk/lmn.py:

    def opq():
        pass
    

When running __main__.py, I get this error:

File "D:\packagetest_main_.py", line 1, in
from . import TestError
ImportError: attempted relative import with no known parent package

Why does from . import TestError generate an error here?

How to solve this problem here and modify the code as little as possible?

I've already read Relative imports in Python 3 but I don't see how to modify my code here to make it work.

1 Answers

One solution seems to move everything in a parent directory parent/ :

parent/
  |- test.py
  |- packagetest/
       |- __init__.py
       |- __main__.py
       |- abc/
           |- __init__.py
       |- ijk/
           |- lmn.py

Then import the package inside parent/test.py:

import packagetest

and then it works.

Related