Why does this circular import fail in Python 2 but not in Python 3?

别等时光非礼了梦想. 提交于 2021-02-08 08:41:22

问题


Assume the following package structure with code inline:

main.py

from a.b import c

a/__init__.py

a/b/__init__.py

a/b/c.py

from a.b import d

a/b/d.py

from a.b import c

python2 main.py gives me an import error:

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    from a.b import c
  File "/home/runner/a/b/c.py", line 1, in <module>
    from a.b import d
  File "/home/runner/a/b/d.py", line 1, in <module>
    from a.b import c
ImportError: cannot import name c

However python3 main.py works fine. Does anyone know what is going on? How do I fix this issue in Python 2? I am trying to convert relative imports to absolute imports!

Python 2 Repl.It

Python 3 Repl.It


回答1:


A quick work around is to move from the format

from a.b import d

to

import a.b.d

I tried it here and it seems to work for Python 2.



来源:https://stackoverflow.com/questions/59831728/why-does-this-circular-import-fail-in-python-2-but-not-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!