Python 将多文件模块中的所有内容导入命名空间

Python Import everything from multiple file module into namespace

假设我有这个:

script.py
module/
    __init__.py # just contains: __all__ = ['foo', 'bar']
    foo.py      # has a function called foo
    bar.py      # has a function called bar

如果从 script.py 我做 from module import * 它有效,但要调用 foo 或 bar 函数我必须做 foo.foo() / bar.bar().

有没有办法在命名空间中包含 foo 和 bar 函数,这样我就可以通过 foo() / bar() 来调用它们?

编辑:接受的答案适用于此示例案例,但经过测试,如果文件名称中包含数字,它似乎不起作用。

例如,如果您将一个名为 bar2.py 的文件和一个名为 hello 的函数添加到模块文件夹,并相应地编辑 __init__.py,那么在 script.py 中您不是'无法在脚本上直接调用 hello 函数(只需执行 hello()),尽管您可以执行 bar2.hello(),这有效但不是我想要的。

编辑:经过大量测试后,我发现删除 __all__ 并保留导入即可。

__init__.py中,写下这两条导入语句:

from .foo import foo
from .bar import bar

编辑:如果你的模块名称中有数字。

from foo2 import foo
from bar2 import bar