2

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.

Basj
  • 41,386
  • 99
  • 383
  • 673
  • A package is to be imported. In the Python console outside the parent folder `packagetest` do an `import packagetest`. If you arbitrarily run (directly) scripts from inside your package, you will almost always get import errors. – progmatico Nov 03 '20 at 14:44

1 Answers1

3

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Basj
  • 41,386
  • 99
  • 383
  • 673