Question

This is my folder:

/Workspace
 somefiles.py
          /foopackage
           __init__.py
           foo1.py
           foo2.py

And the _init_.py contains

from foo1 import foo1
from foo2 import foo2

And I want to import foopackage. I have tried this:

>>>import sys
>>>sys.path.append('/home/username/Workspace')
>>>import foopackage
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/username/Workspace/foopackage/__init__.py", line 1, in <module>
    from foo1 import foo1
ImportError: No module named 'foo1'

I have tried sys.path.append('/home/username/Workspace/foopackage') instead and the thing fixed.

I'm asking do I have to add every package directory to sys.path list to be able to import them?
or something else is wrong?

Was it helpful?

Solution

If you are using Python 3, you need to use explicit relative imports rather than implicit ones, which used to work in Python 2. Try updating foopackage's __init__.py file to be:

from .foo1 import foo1
from .foo2 import foo2

The leading . characters tell Python that foo1 and foo2 are sibling modules, rather than being top level modules that you're referring to absolutely. An alternative would be to use an absolute reference to them:

from foopackage.foo1 import foo1
from foopackage.foo2 import foo2

But personally, I think that's a bit excessive. It will also break if you change the package name at some point in the future (or move to be a subpackage of some other package).

See PEP 328 for more details on the changes to relative imports.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top