How to fix “Attempted relative import in non-package” even with __init__.py

546    Asked by AnushaAcharya in Python , Asked on Jun 1, 2021

I'm trying to follow PEP 328, with the following directory structure:

pkg/
   __init__.py 
   components/ 
      Core.py
      __init__.py 
   tests/ 
     Core_test.py
     __init__.py

In core_test.py I have the following import statement

from ..components.core import GameLoopEvents

However, when I run, I get the following error:

tests$ python core_test.py
 Traceback (most recent call last):
   File "core_test.py", line 3, in  
     from ..components.core import GameLoopEvents 
 ValueError:   Attempted relative import in non-package

Is there anything I'm missing here?

To resolve attempted relative import in non-package you should follow the following:

You need to use the following command like a package which you are not doing while you are running in your CLI:-

      pkg/ __init__.py components/ core.py __init__.py tests/ core_test.py __init__.py

To get the required output as you desire, you are required to use it as a package. And when you are running the command make sure you are outside of directory pkg at the time when you call the package from CLI.

If you want to use import components.core you can use it directly by appending the current directory to sys.path:

if __name__ == '__main__' and __package__ is None: 
from os import sys, path

sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))



Your Answer

Interviews

Parent Categories