'How to organize the module imports from a Python library?
I'm developing a Python library but I'm having some troubles organizing its structure and overall its imports on the init.py files.
Currently, my project has this structure:
module/
├─ submodule/
│ ├─ __init__.py
│ └─ class2.py
├─ __init__.py
├─ class1.py
└─ setup.py
main.py
So, the logic within it is that the class inside class2.py (called Class2) inherits from the class inside class1.py (called Class1, which contains almost only the skeleton for different types of implementations like the one in class2.py) and in the main.py (which is outside the module folder) I'm trying to create an object of the class from class2.py to test the module.
The problem is that I'm receiving this error when I execute the main:
ImportError: cannot import name 'Class1' from partially initialized module 'module' (most likely due to a circular import)
I think that I'm messing up with the imports on the __init__.py files, because I would like to prettify the calling of the classes. I'll explain:
- I want to be able to call
module.Class1directly and not justmodule.class1.Class1, so I've added afrom module.class1 import Class1in the main module__init__.py. - I want to be able to call elements from the submodule just importing the main module, like
module.submodule.Class2, so I've added anfrom module import submoduleto the main module__init__.pyand afrom module.submodule.class2 import Class2to the submodule__init__.py.
And I firmly think that's what is messing things up, so it would be amazing if someone could explain me how this kind of structure should be done and how the imports have to be organized in order to have a clear visibility of the desired elements directly when calling the main module (e.g. when I write module. in the editor and ask it for suggestions to autocomplete I would like to see the suggestions like I've listed above)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
