在加载包时导入包的子模块

Import a submodule of a package while the pacakge is being loaded

我正在导入一个包 foo1.foo2,它的 __init__.py 正在导入一个子模块 foo1.foo2.foo3.bar1,这是一个文件。如果我尝试在该文件中导入 foo1.foo2.foo3.bar2,我会收到以下错误:

AttributeError: module 'foo1' has no attribute 'foo2'

鉴于the use of relative imports is discouraged,我如何在不使用相对导入的情况下解决这个问题?


这是我的包结构和文件内容:

/
├── foo1
│   ├── __init__.py:
│   └── foo2
│       ├── __init__.py: "import foo1.foo2.foo3.bar1"
│       └── foo3
│           ├── __init__.py
│           ├── bar1.py: "import foo1.foo2.foo3.bar2 as bar2"
│           └── bar2.py:
└── main.py: "import foo1.foo2"

运行 python main.py 生成以下错误:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    import foo1.foo2
  File "/foo1/foo2/__init__.py", line 1, in <module>
    import foo1.foo2.foo3.bar1
  File "/foo1/foo2/foo3/bar1.py", line 1, in <module>
    import foo1.foo2.foo3.bar2 as bar2
AttributeError: module 'foo1' has no attribute 'foo2

我正在使用 Python 3.6.0 :: Anaconda 4.3.1

谢谢!

import foo1.foo2.foo3.bar2 as bar2改为from foo1.foo2.foo3 import bar2

然后就可以了。