在Python中,当两个模块试图相互导入时会发生什么?更一般地说,如果多个模块试图在一个循环中导入会发生什么?


另见我能做什么关于“ImportError:不能导入名称X”或“AttributeError:…”(很可能是由于循环导入)”?关于可能导致的常见问题,以及如何重写代码以避免此类导入的建议。参见为什么循环导入看起来在调用堆栈中更上一层,但随后在更下一层引发ImportError ?有关问题发生的原因和方式的技术细节。


当前回答

去年在comp.lang.python上对此进行了很好的讨论。它很彻底地回答了你的问题。

Imports are pretty straightforward really. Just remember the following: 'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line. If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed. If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty. Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__. Take that lot together and you shouldn't get any surprises when importing modules.

其他回答

令我惊讶的是,还没有人提到由类型提示引起的循环导入。 如果只有由于类型提示才有循环导入,则可以以干净的方式避免它们。

考虑main.py,它使用了来自另一个文件的异常:

from src.exceptions import SpecificException

class Foo:
    def __init__(self, attrib: int):
        self.attrib = attrib

raise SpecificException(Foo(5))

专用异常类exceptions.py:

from src.main import Foo

class SpecificException(Exception):
    def __init__(self, cause: Foo):
        self.cause = cause

    def __str__(self):
        return f'Expected 3 but got {self.cause.attrib}.'

这将引发ImportError,因为main.py导入了exception.py,反之亦然,通过Foo和SpecificException。

Because Foo is only required in exceptions.py during type checking, we can safely make its import conditional using the TYPE_CHECKING constant from the typing module. The constant is only True during type checking, which allows us to conditionally import Foo and thereby avoid the circular import error. Something to note is that by doing so, Foo is not declared in exceptions.py at runtime, which leads to a NameError. To avoid that, we add from __future__ import annotations which transforms all type annotations in the module to strings.

因此,我们得到以下Python 3.7+的代码:

from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:  # Only imports the below statements during type checking
   ​from src.main import Foo

class SpecificException(Exception):
   def __init__(self, cause: Foo):  # Foo becomes 'Foo' because of the future import
       ​self.cause = cause

   ​def __str__(self):
       ​return f'Expected 3 but got {self.cause.attrib}.'

在Python 3.6中,future import不存在,所以Foo必须是一个字符串:

from typing import TYPE_CHECKING
if TYPE_CHECKING:  # Only imports the below statements during type checking
   ​from src.main import Foo

class SpecificException(Exception):
   ​def __init__(self, cause: 'Foo'):  # Foo has to be a string
       ​self.cause = cause

   ​def __str__(self):
       ​return f'Expected 3 but got {self.cause.attrib}.'

在Python 3.5及以下版本中,类型提示功能还不存在。 在Python的未来版本中,注解特性可能会成为强制性的,之后就不再需要导入了。这将发生在哪个版本尚未确定。

这个答案是基于Stefaan Lippens的另一个解决方案,它将你从Python的循环导入洞中挖出来。

去年在comp.lang.python上对此进行了很好的讨论。它很彻底地回答了你的问题。

Imports are pretty straightforward really. Just remember the following: 'import' and 'from xxx import yyy' are executable statements. They execute when the running program reaches that line. If a module is not in sys.modules, then an import creates the new module entry in sys.modules and then executes the code in the module. It does not return control to the calling module until the execution has completed. If a module does exist in sys.modules then an import simply returns that module whether or not it has completed executing. That is the reason why cyclic imports may return modules which appear to be partly empty. Finally, the executing script runs in a module named __main__, importing the script under its own name will create a new module unrelated to __main__. Take that lot together and you shouldn't get any surprises when importing modules.

假设您正在运行一个名为request.py的测试python文件 在request.py中,您写入

import request

所以这也很可能是一个循环导入。

解决方案:

只需将测试文件更改为另一个名称,例如aaa.py,而不是request.py。

不要使用其他库已经使用过的名称。

循环导入会终止,但在模块初始化期间,您需要注意不要使用循环导入的模块。

考虑以下文件:

a.py:

print "a in"
import sys
print "b imported: %s" % ("b" in sys.modules, )
import b
print "a out"

b.py:

print "b in"
import a
print "b out"
x = 3

如果你执行a.py,你会得到以下结果:

$ python a.py
a in
b imported: False
b in
a in
b imported: True
a out
b out
a out

在第二次导入b.py时(在第二个ain中),Python解释器不会再次导入b,因为它已经存在于模块dict中。

如果你试图在模块初始化期间从a访问b.x,你会得到一个AttributeError。

将下面的行追加到a.py:

print b.x

则输出为:

$ python a.py
a in                    
b imported: False
b in
a in
b imported: True
a out
Traceback (most recent call last):
  File "a.py", line 4, in <module>
    import b
  File "/home/shlomme/tmp/x/b.py", line 2, in <module>
    import a
 File "/home/shlomme/tmp/x/a.py", line 7, in <module>
    print b.x
AttributeError: 'module' object has no attribute 'x'

这是因为模块是在导入时执行的,在访问b.x时,x = 3行还没有执行,这只会在b退出后发生。

我完全同意pythoneer的回答。但是我偶然发现了一些代码,它们在循环导入时存在缺陷,并在尝试添加单元测试时引起了问题。因此,为了快速修补它而不改变一切,你可以通过动态导入来解决这个问题。

# Hack to import something without circular import issue
def load_module(name):
    """Load module using imp.find_module"""
    names = name.split(".")
    path = None
    for name in names:
        f, path, info = imp.find_module(name, path)
        path = [path]
    return imp.load_module(name, f, path[0], info)
constants = load_module("app.constants")

同样,这不是一个永久性的修复,但可以帮助那些希望在不修改太多代码的情况下修复导入错误的人。

干杯!