【问题标题】:Bundling seperate python modules to create a "Package"捆绑单独的 python 模块以创建“包”
【发布时间】:2014-10-07 09:06:09
【问题描述】:

我一直在创建一些按目的组织的模块,每个模块都包含许多功能。我想将这些单独的模块捆绑到一个更大的“包”中,其他用户可以从共享位置导入。

目前,我将所有模块放在一个名为 python_modules 的文件夹中,并将此路径附加到 os.path 以便我可以根据需要轻松导入各个模块。

但是,我想导入一个包含我所有模块的包,因此我不必单独导入每个模块。我知道我可以将所有模块放入一个文件中,但这似乎不是组织流程的好方法。

目前,我必须在我的python_modules 文件夹中关注文件:

__init__.py
load_data_functions.py 
parse_data_functions.py   
network_functions.py
counting_function.py    
math_functions.py
...
...
other_functions.py

__init__.py 文件为空,其中没有任何内容。其他模块内部都有各种功能,有些是依赖于其他的。例如,network_functions.py 依赖于 load_data_functions.pyparse_data_functions.py

正如我所说,我想将所有这些模块打包成一个更大的包,我可以与其他人共享,因此我们不必单独导入每个模块。

【问题讨论】:

    标签: python module package


    【解决方案1】:

    一个包只是一堆模块。你已经有一个__init__.py 文件,所以python_modules 已经是一个包。您应该能够简单地导入python_modules,然后从每个单独的模块中调用函数load_data_functions.some_function()parse_data_functions.some_other_function()

    【讨论】:

      【解决方案2】:

      假设“我想导入单个包”意味着您希望能够:

      import python_modules
      
      port = python_modules.network_functions.get_port()
      

      您的__init__.py 文件应如下所示:

      from . import load_data_functions
      from . import parse_data_functions
      from . import network_functions
      ...
      

      如果您愿意:

      import python_modules
      
      port = python_modules.get_port()
      

      您的 __init__.py 文件应如下所示:

      from .load_data_functions import *
      from .parse_data_functions import *
      from .network_functions import *
      ...
      

      对于包中的模块相互引用,你可以使用相同的想法,例如在network_funtions.py 的顶部,您需要放置from . import load_data_functions。您应该构造一些东西以避免循环导入。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-06-28
        • 2021-03-13
        • 2020-09-13
        • 2012-06-29
        • 2023-02-03
        • 1970-01-01
        • 2017-01-03
        相关资源
        最近更新 更多