python - 为什么循环导入似乎在调用堆栈中更靠前,但在更靠下的位置引发 ImportError

我收到了这个错误

Traceback (most recent call last):
  File "/Users/alex/dev/runswift/utils/sim2014/simulator.py", line 3, in <module>
    from world import World
  File "/Users/alex/dev/runswift/utils/sim2014/world.py", line 2, in <module>
    from entities.field import Field
  File "/Users/alex/dev/runswift/utils/sim2014/entities/field.py", line 2, in <module>
    from entities.goal import Goal
  File "/Users/alex/dev/runswift/utils/sim2014/entities/goal.py", line 2, in <module>
    from entities.post import Post
  File "/Users/alex/dev/runswift/utils/sim2014/entities/post.py", line 4, in <module>
    from physics import PostBody
  File "/Users/alex/dev/runswift/utils/sim2014/physics.py", line 21, in <module>
    from entities.post import Post
ImportError: cannot import name Post

你可以看到我进一步使用相同的导入语句并且它有效。循环进口有什么不成文的规定吗?如何在调用堆栈的下方使用相同的类?


另见What happens when using mutual or circular (cyclic) imports in Python?有关允许的内容以及导致 WRT 循环导入问题的原因的一般概述。见 What can I do about "ImportError: Cannot import name X" or "AttributeError: ... (most likely due to a circular import)"?用于解决和避免循环依赖的技术。

最佳答案

我认为 answer by jpmc26 ,虽然绝不是,但对循环导入的影响太大了。如果您正确设置它们,它们可以正常工作。

最简单的方法是使用 import my_module 语法,而不是 from my_module import some_object。前者几乎总是有效,即使 my_module 包含导入我们回来。后者仅适用于 my_object 已在 my_module 中定义的情况,而循环导入可能并非如此。

具体到您的情况:尝试更改 entities/post.py 以执行 import Physics 然后引用 physics.PostBody 而不是而不仅仅是 PostBody 直接。同样,将 physics.py 更改为 importentities.post 然后使用 entities.post.Post 而不仅仅是 Post.

关于python - 为什么循环导入似乎在调用堆栈中更靠前,但在更靠下的位置引发 ImportError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22187279/

相关文章:

python - urllib2.HTTPError : HTTP Error 403: Forbi

python - 使用 PyInstaller (--onefile) 捆绑数据文件

python - 如何删除字符串中的前导零和尾随零? Python

python - 在 CentOS 中安装 python 2.6

python - 为什么我不能在打开的文件上调用 read() 两次?

python - 如何绘制正态分布

python - 来自 os.listdir() 的非字母数字列表顺序

python - 新型类中的方法解析顺序(MRO)?

python - SQLAlchemy ORM 转换为 pandas DataFrame

python - 非 ASCII 字符的语法错误