【问题标题】:Importing multiple files as a single module?将多个文件作为单个模块导入?
【发布时间】:2020-01-13 04:33:22
【问题描述】:

过去 4 小时我一直在这里追尾,找不到解决办法。

我的项目有以下模块/包结构。

.
├── app-cli.py
├── tools
│   ├── __init__.py
│   ├── adapters
│   │   ├── __init__.py
│   │   ├── cli.py
│   │   ├── web.py
│   ├── utils
│   │   ├── __init__.py
│   │   ├── core.py
│   │   │   ├── my_public_method()
│   │   ├── io.py
│   │   │   ├── some_other_public_method()

我要做的是将utils 内的所有内容捆绑在utils 名称空间内。

所以当我在主级别执行import tools 时,我可以访问 util 函数:

tools.utils.my_public_method()
tools.utils.some_other_public_method()

代替:

 tools.utils.core.my_public_method()
 tools.utils.io.some_other_public_method()

我一直在编辑__init__.py,弄乱了导入的级别,试图创建一个快捷方式但没有成功。

【问题讨论】:

    标签: python module package


    【解决方案1】:

    utils 包内的__init__.py 中,您可以添加

    from .core import my_public_method
    from .io import some_other_public_method
    

    然后你可以这样做:

    import tools.utils
    
    tools.utils.my_public_method()
    tools.utils.some_other_public_method()
    

    【讨论】:

    • 有没有办法做到from .core import *from .io import *,这样我就可以在core.pyio.py 中拥有__all__
    • 是的,您只需将from .core import my_public_method 更改为from .core import *
    • 啊,是的,它有效。出于某种原因,flake8from .core import * 位不满意。但它有效。我想我不需要 utils/__init__.py 文件中的 __all__ 位。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-09
    • 1970-01-01
    相关资源
    最近更新 更多