【问题标题】:Why does this circular import fail in Python 2 but not in Python 3?为什么这种循环导入在 Python 2 中失败,而在 Python 3 中却没有?
【发布时间】:2020-01-21 07:07:09
【问题描述】:

假设以下包结构内嵌代码:

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 给我一个导入错误:

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

但是python3 main.py 工作正常。有谁知道发生了什么?如何在 Python 2 中解决此问题?我正在尝试将相对导入转换为绝对导入!

Python 2 Repl.It

Python 3 Repl.It

【问题讨论】:

  • 我认为这可能属于命名空间包与 Python 3 中的常规包的职权范围。this 示例是否回答了您的问题?
  • @soyapencil,这很有趣,我认为它似乎与命名空间包的想法有关 - 让我探索一下。感谢 PEP。

标签: python python-3.x python-2.x circular-dependency


【解决方案1】:

一个快速的解决方法是从格式移动

from a.b import d

import a.b.d

我试过here,它似乎适用于 Python 2。

【讨论】:

  • 知道它是否是 Python 2 中的错误吗?
猜你喜欢
  • 2020-01-02
  • 2016-04-20
  • 2015-05-20
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
相关资源
最近更新 更多