Python import error solution. (Need a better approach)

Viewed 110

My Dir structure is like this

├── server.py
└── Utils
    ├── A.py
    ├── __init__.py
    ├── B.py

Inside server.py, one import is there

from Utils.B import SomeClass

Inside B.py there's also one import

from .A import SomeClass

While running server.py, it's running fine. But while running B.py inside Utils, it's throwing error:

ModuleNotFoundError: No module named '__main__.A'; '__main__' is not a package

Then removing the dot and then running, B.py is working fine but server.py is throwing error. Can there be any solution which will run both fine?

1 Answers

I would try staying away from relative imports (the ones with a leading .).

A generally good file structure looks like this:

Project
├── setup.py
├── README.md
└── project
    ├── __init__.py
    ├── server.py
    └── Utils
        ├── __init__.py
        ├── A.py
        └── B.py

The main takeaways here are:

  • There's a main folder called Project holding all the files.
  • Directly inside that one we put all meta-files such as setup.py and README.md and all that jazz. We don't put any code here because we don't want this folder to be seen as a package (no dunder init file).
  • We create a second folder, having the same name but with lower case (project), this is the main python package as we put a dunder init file in here. This is the base for all our imports.
  • Then with every import we define the full path like this: from project.Utils.A import SomeClass.
  • If you want that class to be easily imported from your package then you can write from project.Utils.A import SomeClass inside the first dunder init file, after which you can do from project import SomeClass whenever you need it.

This answer is also really good and relevant: https://stackoverflow.com/a/3419951/3936044

Related