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


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


当前回答

Ok, I think I have a pretty cool solution. Let's say you have file a and file b. You have a def or a class in file b that you want to use in module a, but you have something else, either a def, class, or variable from file a that you need in your definition or class in file b. What you can do is, at the bottom of file a, after calling the function or class in file a that is needed in file b, but before calling the function or class from file b that you need for file a, say import b Then, and here is the key part, in all of the definitions or classes in file b that need the def or class from file a (let's call it CLASS), you say from a import CLASS

这是可行的,因为您可以导入文件b,而无需Python执行文件b中的任何导入语句,因此您可以避免任何循环导入。

例如:

文件:

class A(object):

     def __init__(self, name):

         self.name = name

CLASS = A("me")

import b

go = B(6)

go.dostuff

文件b:

class B(object):

     def __init__(self, number):

         self.number = number

     def dostuff(self):

         from a import CLASS

         print "Hello " + CLASS.name + ", " + str(number) + " is an interesting number."

喉咙痛。

其他回答

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

考虑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的循环导入洞中挖出来。

正如其他答案所描述的,这种模式在python中是可以接受的:

def dostuff(self):
     from foo import bar
     ...

这将避免在文件被其他模块导入时执行import语句。只有当存在逻辑循环依赖时,这才会失败。

大多数循环导入实际上不是逻辑循环导入,而是会引发ImportError错误,这是因为import()在调用时计算整个文件的顶级语句的方式。

如果你确实想要你的导入在顶部,这些ImportErrors几乎总是可以避免的:

考虑这个循环导入:

应用一个

# profiles/serializers.py

from images.serializers import SimplifiedImageSerializer

class SimplifiedProfileSerializer(serializers.Serializer):
    name = serializers.CharField()

class ProfileSerializer(SimplifiedProfileSerializer):
    recent_images = SimplifiedImageSerializer(many=True)

应用程序B

# images/serializers.py

from profiles.serializers import SimplifiedProfileSerializer

class SimplifiedImageSerializer(serializers.Serializer):
    title = serializers.CharField()

class ImageSerializer(SimplifiedImageSerializer):
    profile = SimplifiedProfileSerializer()

来自David Beazleys的精彩演讲:模块和包:生存和死亡!PyCon 2015, 1:54:00,这里是一个处理python循环导入的方法:

try:
    from images.serializers import SimplifiedImageSerializer
except ImportError:
    import sys
    SimplifiedImageSerializer = sys.modules[__package__ + '.SimplifiedImageSerializer']

它尝试导入SimplifiedImageSerializer,如果ImportError被引发,因为它已经被导入,它将从importcache中拉出它。

PS:你必须用David Beazley的声音来阅读整篇文章。

如果你导入foo(在bar.py内部)和导入bar(在foo.py内部),它会工作得很好。在实际运行任何东西时,两个模块都将完全加载,并将相互引用。

问题是当你做from foo import abc(在bar.py内)和from bar import xyz(在foo.py内)时。因为现在每个模块都需要另一个模块已经被导入(以便导入的名称存在),然后才能导入它。

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

import request

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

解决方案:

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

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

去年在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.