Python 3 - 将子包子模块名称导入顶级包

2024-09-28 03:11:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个Python repo,包结构如下:

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

在每个子包__init__.py中,我使用from .<submodule name> import *导入子模块名称,例如在utils.__init__.py中我们有

^{pr2}$

现在在主包inttools.__init__.py中,我将以以下方式导入所有子包子模块名称:

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

其思想是,当导入inttools包时,所有子包子模块名称都可以在包名称空间中使用,但这失败了。例如,在ipythoni中cdintttools所在的目录(/Users/srm/dev)并执行以下操作。在

在[1]:导入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'

Tags: 模块frompyimport名称initutilsprimes
1条回答
网友
1楼 · 发布于 2024-09-28 03:11:48

包是inttools,因此子包是inttools.utilsinttools.primes

您可以在__init__.py中使用这个绝对路径,也可以使用相对路径(.utils.primes等)

相关问题 更多 >

    热门问题