0

I have a folder mypackage at the location /mypath/mypackage/, and it contains an __init__.py file which is empty. mypackage contains two python files: packagefile1 and packagefile2, and packagefile2 contains import packagefile1.

When I then call a python script at /myotherpath/script.py which contains import packagefile2, it correctly finds packagefile2, but I get an error :

Traceback (most recent call last):
  File "/myotherpath/script.py", line 5, in <module>
    from mypackage import packagefile2
  File "/mypath/packagefile2.py", line 16, in <module>
    import packagefile1
ModuleNotFoundError: No module named 'packagefile1'

However, I don't get this error when I call packagefile2 directly, so it must be because I am not calling the scripts in the mypackage folder.

What is the appropriate way to solve this?

I have read here that the solution is to change import packagefile1 to import .packagefile1, but then I read here that relative imports using . are outdated. So what is the appropriate way to import modules within the same package?

ps: /mypath/ is part of the pythonpath variable (when I command env | grep -i python in bash, it shows PYTHONPATH=:/mypath/).

user56834
  • 244
  • 4
  • 19
  • This [link](https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.html) may help you make some sense of how python imports work. – frippe Dec 13 '21 at 14:06
  • you should try this: in the file "/mypath/packagefile2.py": from mypackage import packagefile1 – marie Dec 13 '21 at 14:07
  • @frippe, the link you sent clarified a lot, thank you :) – user56834 Dec 14 '21 at 05:36

0 Answers0