问题
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