Packagelevel导出,循环依赖项

2024-10-03 21:24:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下包裹:

foo/
    __init__.py:
        from .body import UsefulClass
        from .another import AnotherClass

    body.py:

        from . import utll
        class UsefulClass:
            util.do_something()

    another.py:

        class AnotherClass: ...

    util.py:

        def do_something...

   

其思想是,当有人导入foo时,他们应该能够使用foo.UsefulClass,而不必担心包的内部结构。换句话说,我不希望他们导入foo.body,只是foo

然而,当我在body.py中执行from . import util时,这也会导入__init__.py,这反过来又会再次导入body。我意识到python可以很好地处理这种情况,但是我不喜欢这种明显的循环依赖

有没有更好的方法在包级别导出内容,而不在导入中创建循环依赖关系

PS:我希望避免函数内导入


Tags: frompyimportfooinitdefutilanother
1条回答
网友
1楼 · 发布于 2024-10-03 21:24:03

我认为你最初的假设是错误的。如果使用当前设置执行import foo语句,body.py将只导入一次,这可以通过将打印语句作为这些文件中的第一行来显示:

目录foo的布局(我省略了另一个.py,因为它的存在与否无关):

enter image description here

文件\uuuu init\uuuuu.py

print('__init__.py imported')

from .body import UsefulClass

文件body.py

print('body.py imported')

from . import util

class UsefulClass:
    x = util.do_something()

文件util.py

def do_something():
    return 9

最后:

Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import foo
__init__.py imported
body.py imported
>>> foo.UsefulClass.x
9
>>>

相关问题 更多 >