0

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:

  • Running main.py: ImportError: attempted relative import beyond top-level package
  • Running SomeHelper.py in the interactive window: ImportError: attempted relative import with no known parent package

Thanks in advance!

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I edited the question to add some information. The __init__.pys are empty, SomeHelper.py only uses built-in imports.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.