循环内部引用子模块

时间:2012-07-22 07:21:01

标签: python python-3.x

结构如下:模块test包含两个子模块test.footest.bar

test.foo有一个使用inc()的函数test.bar.bar()所以基于python文档from . import bar是包含它的正确方法,这可以按预期工作。

test.bar但是,也有一个使用inc2的函数test.foo.foo,但是当使用from . import foo时,这两个模块都会中断。

实现这一目标的正确方法是什么?我在python文档或搜索中找不到。

代码

测试/ _ 初始化 _。PY

#empty

测试/ foo.py

from . import bar

def foo():
    print("I do foo")

def inc():
    print(bar.bar())

测试/ bar.py

from . import foo

def bar():
    print("I do bar")

def inc2():
    print(foo.foo())

错误1

>>> import test.foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test/foo.py", line 1, in <module>
    from . import bar
  File "test/bar.py", line 1, in <module>
    from . import foo
ImportError: cannot import name foo

错误2

>>> import test.bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "test/bar.py", line 1, in <module>
    from . import foo
  File "test/foo.py", line 1, in <module>
    from . import bar
ImportError: cannot import name bar

1 个答案:

答案 0 :(得分:4)

解决方案是将两个模块所需的代码分解为由两者导入的第三个模块。例如,将foo函数放入第三个模块。

之前有很多StackOverflow问题,例如Circular import dependency in Python。另请参阅http://effbot.org/zone/import-confusion.htm#circular-imports

相关问题