【问题标题】:How do I re-organise a python module to not reflect the directory structure?如何重新组织 python 模块以不反映目录结构?
【发布时间】:2020-03-04 13:56:02
【问题描述】:

我正在编写代码生成器并希望能够导出到不同的文件类型。 foo 模块包含不同类(subA、subA、subC)的 sn-ps。 bar.pybaz.py 持有不同语言的 sn-ps。
我发现导入foo.bar 并获取bar 语言的所有sn-ps 比必须为每个类导入bar 更方便。
同样,我宁愿将特定类的所有 sn-ps 放在同一目录中,因此有以下组织

foo
| __init__.py
+ subA
| | __init__.py
| | bar.py
| ` baz.py
+ subB
| | __init__.py
| | bar.py
| ` baz.py
` subC
  | __init__.py
  | bar.py
  ` baz.py

我希望能够像这样导入: from foo.bar import subA 应该让我访问foo/subA/bar.py

我认为我需要在 foo/__init__.py 中进行重新组织,但我不知道具体要做什么。我的猜测是我需要创建一个空模块或命名空间,甚至只是我用所需模块填充的对象。
但我不断收到语法错误。

目前我的foo/__init__.py 看起来像这样

import foo.subA.bar
import foo.subB.bar
import foo.subC.bar

class bar:
    def __init__(self):
        self.subA = foo.subA.bar
        self.subB = foo.subB.bar
        self.subC = foo.subC.bar

这让我可以导入 foofoo.bar 但尝试访问 foo.bar.subA给我

AttributeError: type object 'bar' has no attribute 'subA'

我不确定我在这里缺少什么,所以我愿意接受建议。

【问题讨论】:

    标签: python module


    【解决方案1】:

    通过引入处理别名的包,我能够使它足够方便地工作,如下所示:

    foo
    | __init__.py
    + subA
    | | __init__.py
    | | bar.py
    | ` baz.py
    + subB
    | | __init__.py
    | | bar.py
    | ` baz.py
    + subC
    | | __init__.py
    | | bar.py
    | ` baz.py
    | bar.py
    ` baz.py
    

    bar.py 看起来像这样:

    import foo.subA.bar as subA
    import foo.subB.bar as subB
    import foo.subC.bar as subC
    

    这使我可以import foo.bar 并获得指向foo/subA/bar.pyfoo.bar.subA

    这不是我的想法,因为它需要我在 bar.py 中维护一个别名列表,我可以不用它,但它会做。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多