代码之家  ›  专栏  ›  技术社区  ›  Brendan

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

  •  6
  • Brendan  · 技术社区  · 16 年前

    我有一个python包 mymodule 有一个子包 utils (即一个子目录,其中包含每个有一个函数的模块)。这些函数的名称与它们所在的文件/模块的名称相同。

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

    from mymodule.utils import a_function

    但奇怪的是,有时我可以使用上述符号导入函数,但有时我不能。但是,我还不知道为什么(例如,最近,我重命名了一个函数及其所在的文件,并在 utils.__init__.py 但它不再作为函数(而不是模块)导入到我的一个脚本中。

    这个 实用程序初始化 读起来像,

    __all__ = ['a_function', 'b_function' ...]
    from a_function import a_function
    from b_function import b_function
    ...
    

    mymodule.__init__.py 没有提到 乌迪斯

    思想?

    1 回复  |  直到 16 年前
        1
  •  7
  •   Daniel Stutzbach Edward Leno    16 年前

    您的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
    

    当utils.py首次导入a_函数模块时,utils.b_函数是模块而不是函数。在执行最后一行之前声明“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_函数 在导入期间。