【问题标题】:Importing a function/class from a Python module of the same name从同名的 Python 模块导入函数/类
【发布时间】:2010-03-25 21:24:26
【问题描述】:

我有一个 Python 包 mymodule 和一个子包 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
...

mymodule.__init__.py 没有引用 utils

想法?

【问题讨论】:

    标签: python import module


    【解决方案1】:

    您的 utils 函数是否需要导入其他 utils 函数? (或导入导入其他实用程序功能的其他模块)。例如,假设 a_function.py 包含“from mymodule.utils import b_function”。这是你的 utils.py 和一堆额外的 cmets:

    # 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
    

    当 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

    【讨论】:

    • 那么import mymodule.utils as utilsfrom mymodule import utils有什么区别?
    • @Mike DeSimone:好点。我相应地更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2011-10-01
    • 2015-03-05
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    相关资源
    最近更新 更多