Reputation: 340
I am struggling with imports in Python. Currently, this is my file structure:
.
├── my_project
│ ├── helpers
│ │ ├── SomeHelper.py
│ │ └── __init__.py
│ ├── CalculateStuff
│ │ ├── __init__.py
│ │ └── CalculateX.py
│ ├── __init__.py
│ └── main.py
├── poetry.lock
├── pyproject.toml
└── README.md
In CalculateStuff.CalculateX.py
, there is the class CalculateX
which requires SomeHelper
.
Currently, that import looks like this:
from helpers.SomeHelper import SomeHelper
In main.py
:
from CalculateStuff.CalculateX import CalculateX
x_calculator = CalculateX()
x_calculator.do_something()
This works fine, when I run the main script, e.g. use poetry run python my_project/main.py
.
However, the different parts are under development. I want to use CalculateX.py
as an etrypoint, too, and have it find its imports as well as run some test code (with if __name__ == "__main__":[...]
.
Furthermore, I want to be able to use the Python interactive window (within VS Code) to execute the code in any of the files in order to develop everything step by step. Unfortunately, I always get import errors.
How to achieve this, without tampering around with sys.path
?
The imports in my CalculateStuff/CalculateX
:
# Generic python imports
from helpers.SomeHelper import SomeHelper
If I change it to from ..helpers.SomeHelper import SomeHelper
, I get import errors:
ImportError: attempted relative import beyond top-level package
ImportError: attempted relative import with no known parent package
Thanks in advance!
Upvotes: 0
Views: 31
Reputation: 26
The .py should work on its own individually if the imports are defined properly. Without seeing the files, it is hard to determine the exact cause. But, make sure the imports are relative to the file's location.
Upvotes: 0