w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
python : how to import packages?

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.

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.