1

With such a project structure:

- code
  - modules
    - tests
      test_data_quality_service.py
    data_quality_service.py
  - web

I keep getting errors when I try to import class DataQualityChecker from data_quality_service. I get these erros both for absolute

from code.modules.data_quality_service import DataQualityChecker
E   ModuleNotFoundError: No module named 'code.modules'; 'code' is not a package

and relative imports:

from ..data_quality_service import DataQualityChecker
E   ImportError: attempted relative import with no known parent package

How can I fix it? It's happening in PyCharm, I'm running unit tests and I also tried pytest but I had the same error.

dark_matter88
  • 307
  • 3
  • 14
  • From wich directory are you executing the tests? Did you create `__init__.py` files? – Fran Arenas Aug 12 '22 at 13:40
  • Yes, I did. I've changed the project structure a little bit but only adding import sys sys.path.append("..") before imports solved the problem – dark_matter88 Aug 15 '22 at 10:36
  • That means that you are executing the script in the wrong path. Try to execute the script from the root of the project – Fran Arenas Aug 15 '22 at 11:02

2 Answers2

1

You need to add an __init__.py file (it can be empty) on each folder to mark it as a python package.

- code
  - modules
    - tests
      test_data_quality_service.py
      __init__.py
    data_quality_service.py
    __init__.py
  - web

Also, probably you should consider a better project structure

Fran Arenas
  • 639
  • 6
  • 18
0

In python installation directory there is file python38._pth You have to give module path code.modules

Raja M
  • 14
  • 1
  • This can be done with the flag -m when executing the python script. Btw, with an IDE as pycharm this is not necesary if you use it to execute the code – Fran Arenas Aug 12 '22 at 13:47