1

I am using VSCode editor and getting an error while importing a module from a sub-directory that is inside the same parent directory as shown in the screenshot:

enter image description here

Traceback (most recent call last):
  File "D:\Test\Packages\MyPackage\B\b.py", line 2, in <module>
    import MyPackage.A.a
ModuleNotFoundError: No module named 'MyPackage'

As you can also see I have __init__.py in every directory which is just a 0 bytes file to tell python that the directory is a package.

I was able to solve this using the following line:

sys.path.append("D:/Test/Packages")

I heard there's a better way to do it. Is there another but better way to do it?

cpx
  • 17,009
  • 20
  • 87
  • 142
  • you heard wrong ... use the path ... but you could just `sys.path.append("..")` if its always the parent ... or run it from the D:\Test\Packages folder (`cd D:\Test\Packages; python MyPackage/B/b.py`) – Joran Beasley Jan 24 '21 at 19:44
  • from ..A import a (using relative imports) https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time – frab Jan 24 '21 at 19:44
  • For example `python -m MyPackage.B.b`, is that not what I need to configure in VSCode in order to do it another way? – cpx Jan 24 '21 at 19:47
  • Did you try import Package.MyPackage.A.a? – daniboy000 Jan 24 '21 at 19:48
  • Yes, that gives `ModuleNotFoundError: No module named 'Packages'`. – cpx Jan 24 '21 at 19:51
  • 1
    afaik you cannot use relative imports in an entry point script? @frab (I could be wrong ... i know in py2 that was true) – Joran Beasley Jan 24 '21 at 19:53
  • @frab: `ImportError: attempted relative import with no known parent package` that's an error. – cpx Jan 24 '21 at 19:56
  • Ever heard of "pip editable installs", the pythonic way to solve the issue? – Peter Jan 24 '21 at 21:43

0 Answers0