从同名的Python模块导入函数/类

Bre*_*dan 6 python import module

我有一个mymodule包含子包的Python包utils(即包含每个都带有函数的模块的子目录).这些函数与它们所在的文件/模块具有相同的名称.

我希望能够访问如下功能,

from mymodule.utils import a_function

但奇怪的是,有时我可以使用上面的表示法导入函数,但有时我不能.我无法弄清楚为什么(最近,例如,我重命名了一个函数及其所在的文件并在文件中反映了这个重命名,utils.__init__.py但它不再作为函数(而是作为模块)导入其中一个我的脚本.

utils.__init__.py读取类似,

__all__ = ['a_function', 'b_function' ...]
from a_function import a_function
from b_function import b_function
...
Run Code Online (Sandbox Code Playgroud)

mymodule.__init__.py 没有提及 utils

想法?

Dan*_*ach 7

您的utils函数是否需要导入其他utils函数?(或导入导入其他utils函数的其他模块).例如,假设a_function.py包含"from mymodule.utils import b_function".这是你的utils.py,附带一些额外的评论:

# interpreter is executing utils.py
# Right now, utils.a_function and utils.b_function are modules

# The following line executes the a_function module, 
# then rebinds a_function to a_function.a_function
from a_function import a_function 

# The following line executes the b_function module, 
# then rebinds b_function to b_function.b_function
from b_function import b_function
Run Code Online (Sandbox Code Playgroud)

当utils.py首次导入a_function模块时,utils.b_function是一个模块而不是一个函数.在执行最后一行之前声明"from mymodule.utils import b_function"的任何模块最终将引用b_function模块而不是b_function函数.

总的来说,我发现这个from somemodule import something成语对任何大型项目都充满了危险.它对于短脚本很有用,但是一旦开始引入循环导入依赖项,就会遇到问题,需要注意使用它的位置.

作为安全和打字保存之间的妥协,我会使用from mymodule import utils然后打电话utils.a_function().这样,你总是会得到的对象绑定到utils.a_function 现在,而不是无论发生在绑定到utils.a_function导入过程中.