srm
srm

Reputation: 597

Python 3 - importing subpackage submodule names into top package

I've got a Python repo with the following package structure:

inttools/
├── LICENSE
├── README.md
├── __init__.py
├── complex
│   ├── __init__.py
│   └── complex.py
├── divisors
│   ├── __init__.py
│   └── divisors.py
├── primes
│   ├── __init__.py
│   └── primes.py
├── sequences
│   ├── __init__.py
│   ├── champernowne.py
│   ├── collatz.py
│   ├── general.py
│   └── ulam.py
├── special_numbers
│   ├── __init__.py
│   ├── hilbert.py
│   └── polygonal.py
├── special_sets
│   ├── __init__.py
│   ├── cyclic.py
│   └── polygonal.py
└── utils
    ├── __init__.py
    └── utils.py

In each of the subpackage __init__.pys I'm importing the submodule names using from .<submodule name> import *, e.g. in utils.__init__.py we have

from .utils import *

and now in the main package inttools.__init__.py I am importing all the subpackage submodule names in the following way:

from utils import *
from primes import *
...
...

The idea is that when the inttools package is imported all subpackage submodule names are available in the package namespace, but this fails. For example in iPython I cd to the directory in which intttools lives (/Users/srm/dev) and do the following.

In [1]: import inttools

ImportError                               Traceback (most recent call last)
<ipython-input-1-52c9cc3419fb> in <module>()
----> 1 import inttools

/Users/srm/dev/inttools/__init__.py in <module>()
----> 1 from utils import *
      2 from primes import *
      3 from divisors import *
      4 from complex import *
      5 from sequences import *

ImportError: No module named 'utils'

Upvotes: 0

Views: 474

Answers (1)

Thyrst
Thyrst

Reputation: 2568

The package is inttools, therefore subpackages are inttools.utils, inttools.primes etc.

You can either use this absolute path in __init__.py, or relative path (.utils, .primes etc.)

Upvotes: 1

Related Questions