2

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?

Swain Subrat Kumar
  • 445
  • 1
  • 4
  • 14

1 Answers1

1

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

Mandera
  • 2,647
  • 3
  • 21
  • 26
  • I used the file structure. Now it's showing: Traceback (most recent call last): File "server.py", line 1, in from demo.utils.b import B ModuleNotFoundError: No module named 'demo' – Swain Subrat Kumar Aug 17 '20 at 15:42
  • In your example you had capitalized `Utils` and `B.py`, if it's not that then I cannot really help you without you showing your exact structure and code, you'll have to ask another question in that case – Mandera Aug 17 '20 at 16:08
  • It's the same structure. I just changed some_function to B and utils to Utils. If this is the case of error, I'll change it – Swain Subrat Kumar Aug 17 '20 at 16:18