2

I'm trying to build a package that has the following structure,

  • __init__.py
  • a.py
  • subpackage
    • __init__.py
    • b.py

a.py file contains a class from b.py, let say "classX". So, a.py has the following line at the beginning of file,

from subpackage.b import classX

The problem is that, when I try to use this entire package from outside, I get the error "no module named 'b'".

How can I fix this problem?

arhr
  • 1,505
  • 8
  • 16
m.a.a.
  • 137
  • 1
  • 9

1 Answers1

0

Your directory structure should be

package (choose whatever name you want for the high-level package name)
    __init__.py
    a.py
    subpackage
        __init__.py
        b.py

The parent directory of package needs to be in the sys.path list of directories to be searched for resolving imports. This can be accomplished by having that directory being the current working directory when you invoke whatever program you are running or adding the directory to the PYTHONPATH environment variable or modifying sys.path at runtime before doing your imports.

Then a.py should be either:

from package.subpackage.b import classX

or

from .subpackage.b import classX
Booboo
  • 38,656
  • 3
  • 37
  • 60