0

I'm working on migrating an exsting Python 2.7 project to Python 3.9. I'm facing a directory structure-related issue in Python 3.

My current project directory structure is:

├───project
│ ├───core
| +--__init__.py
| +--main.py
| +--settings.py
│ ├───jobs
| +--job.py

main.py:

import settings
class Main:
 def __init__(self, a=None, b=settings.B):
 self.a = a
 self.b = b
 def start(self):
 print(self.a, self.b)

job.py:

import sys
# sys.path.insert(0, '../core/')
from core.main import Main
from core import settings
main = Main(settings.A)
main.start()

There is no issues with this structure when Python 2.7 interpreter is used, but in Python 3.9 I see the following error when job.py is executed:

 File "project\core\main.py", line 1, in <module>
 import settings
ModuleNotFoundError: No module named 'settings'

The issue is fixable by uncommenting the code on line #2 of the job.py script, but I would like to avoid hardcoding folder values like that. I would appreciate if someone could provide an alternative approach and an explanation why it's behaving this way in the newer Python version.

asked May 26, 2022 at 18:51

1 Answer 1

1

Due to ambiguity absolute import was removed in python3 for such use case. (This explains it very well: Changes in import statement python3)

You can use relative import for this use case maybe - https://docs.python.org/3/reference/import.html#package-relative-imports

answered May 26, 2022 at 19:08
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.