Correct python project structure and import statements

143 Views Asked by At

I understand that this question surely is a duplicate (maybe "multicate" is more accurate). However, I'm asking because I cannot transfer the answer to my problem. Also, most of the other examples given use somehow a "parallel" file-structure. Not mine.

We do have an Utils repo holding a library with some classes and also a tools section that use some of these classes.

├── Utils
│   ├── __init__.py
│   ├── Library
│   │   ├── __init__.py
│   │   ├── SomeClasses.py
│   │   └── HelperFunctions.py
│   └── Tools
│       ├── __init__.py
│       ├── ToolCategory1
│       │   ├── __init__.py
│       │   └── ...
│       └── ToolCategory2
│           ├── __init__.py
│           ├── simplify.py
│           └── check.py

So let's say I need a certain class from ./Library/SomeClasses.py in ./Tools/simplify.py that I intend to execute from anywhere using py absolute/path/to/Utils/Tools/simplify.py.

What is the correct import statement in there? Let's set Python Version newer than 3.8 as a constraint. To avoid any hassle, I used symlinks so far, to bring the structure I knew it work. I don't like that solution that much.

I learnt:

1. The update-path-way

import sys
from pathlib import Path
sys.path.insert(0, Path(__file__).parent.parent.parent)
from Library.SomeClasses import *

2. The relative import path way

import ...Library.SomeClasses import *

However, none of these work stable for me (means from the console and on different locations the file is being invoked). To be more precise, the latter one is working if I execute it from PyCharm, but not from the console.

Thank you in advance!

0

There are 0 best solutions below