我有以下包裹:
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:我希望避免函数内导入
我认为你最初的假设是错误的。如果使用当前设置执行 和body.py将只导入一次,这可以通过将打印语句作为这些文件中的第一行来显示:
import foo
语句,目录foo的布局(我省略了另一个.py,因为它的存在与否无关):
文件\uuuu init\uuuuu.py:
文件body.py:
文件util.py:
最后:
相关问题 更多 >
编程相关推荐