0

I am create a little package of packages to facilitate some work. The problem I am encountering is this error message ImportError: Attempted Relative Import With No Known Parent Package. I have been googling around as to how to resolve this, but I have not found anything that works.

So here is the package structure. Notice that the applications are in these subfolders, and hey draw upon some modules that are at a higher level.

- Project_folder
  - Callbacks
    - PrintingCallback.py
    - LoggingCallback.py

  - DataModules
    - preprocess.py
    - utils.py

  - app1
    - app1.py

  - app2
    - app2.py

  - app3
    - app3.py

So the main action is in the app1.py or app2.py command line app. I am using the hydra framework for the CLI. BUT, those python apps need to import the Callbacks and DataModules folder and the files in there. So how would I go about importing the preprocess.py module into app1.py? That is the real question.

I tried using an absolute path, like from Callback.LoggingCallback import LoggingCallback, then then that still generated the error message ImportError: Attempted Relative Import With No Known Parent Package. So is there a better way to do this that is reasonably pythonic?

krishnab
  • 9,270
  • 12
  • 66
  • 123
  • Please post the exact Traceback, especially since the usage of the absolute import should not produce that message, my suspicion is whatever import statement inside `LoggingCallback` may be the culprit. In any case, you should turn your project into an [actual package via a `setup.py`](https://stackoverflow.com/a/39811884/) if you want imports to work correct in a more general case. – metatoaster Jul 05 '21 at 05:19
  • You should create a proper Python project structure. This usually means to have the main module (the one started) in the project root. This will add the project root folder to the `PYTHONPATH` and make it the base for imports. Also you will have to add `__init__.py` files to your sub folder. This will make them a package and therefore importable. – Klaus D. Jul 05 '21 at 05:26
  • Thanks @metatoaster and Klaus. Yeah the idea of creating a separate package does make sense. Sides like the best idea. That is pretty easy to do, so I will give that a shot. Thanks for the suggestion. – krishnab Jul 05 '21 at 14:02

0 Answers0