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.
CodePudding user response:
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