Python:交叉导入模块失败

时间:2019-05-12 09:01:36

标签: python import module runtime-error

交叉导入时,模块导入似乎失败。

我的prog.py文件:

import sys
sys.path.append(".")
from m1 import f1

还有m1.py

from m2 import f2

def f1():
  pass

还有m2.py

from m1 import f1

def f2():
  pass   

我的模块m1需要使用模块2中的某些功能,而模块2需要使用模块1中的某些功能,因此我以上述方式导入它们。但是Python(python3)不允许我这样做。这是例外:

Traceback (most recent call last):
  File "prog.py", line 3, in <module>
    from m1 import f1
  File "/temp/m1.py", line 1, in <module>
    from m2 import f2
  File "/temp/m2.py", line 1, in <module>
    from m1 import f1
ImportError: cannot import name 'f1'

我知道这是交叉导入,但是如何解决此问题?

2 个答案:

答案 0 :(得分:2)

您可以将交叉导入移动到文件的末尾,这样就已经定义了导出的所有内容:

还有m1.py:

def f1():
  pass

from m2 import f2

还有m2.py:

def f2():
  pass

from m1 import f1

答案 1 :(得分:0)

这里有一个解决方案,将导入移动到函数中,而不是在文件顶部导入,但是在顶部导入更美观。

参考: https://stackoverflow.com/a/17226057/5581893

相关问题