Python 将模块移动到子目录中(不破坏现有的导入结构)

Python moving modules into sub directory (without breaking existing import structure)

假设我正在编写目录结构如下的库代码:

- mylibrary/
|
|-----foo.py
|-----bar.py
|-----baz.py
|-----__init__.py

为了更好地组织,我创建了一个子目录:

- mylibrary/
|
|-----foobar/
|     |-----foo.py
|     |-----bar.py
|-----baz.py
|-----__init__.py

我希望所有客户端代码在没有更新的情况下继续工作,所以我想更新 init.py 以便导入不会中断。

我试过将它添加到 init.py:

from foobar import foo

现在如果我打开 shell 我可以做:

from mylibrary import foo
print(foo.Foo)

但是如果我这样做:

from mylibrary.foo import Foo

我收到没有名为 mylibrary.foo 的模块错误。 这是我实际示例的回溯:

Type "help", "copyright", "credits" or "license" for more information.
>>> from global_toolkit import section
>>> section.Section
<class 'global_toolkit.serialization.section.Section'>
>>> from global_toolkit.section import Section
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'global_toolkit.section'
>>> 

任何人都可以解释这种行为吗?

将此添加到您的 __init__.py 中:

from .foobar import foo, bar
import sys
for i in ['foo','bar']:
  sys.modules['mylib.'+i] = sys.modules['mylib.foobar.'+i]

现在,from mylib.foo import Foo 应该可以了。