在Python中,当两个模块试图相互导入时会发生什么?更一般地说,如果多个模块试图在一个循环中导入会发生什么?
另见我能做什么关于“ImportError:不能导入名称X”或“AttributeError:…”(很可能是由于循环导入)”?关于可能导致的常见问题,以及如何重写代码以避免此类导入的建议。参见为什么循环导入看起来在调用堆栈中更上一层,但随后在更下一层引发ImportError ?有关问题发生的原因和方式的技术细节。
在Python中,当两个模块试图相互导入时会发生什么?更一般地说,如果多个模块试图在一个循环中导入会发生什么?
另见我能做什么关于“ImportError:不能导入名称X”或“AttributeError:…”(很可能是由于循环导入)”?关于可能导致的常见问题,以及如何重写代码以避免此类导入的建议。参见为什么循环导入看起来在调用堆栈中更上一层,但随后在更下一层引发ImportError ?有关问题发生的原因和方式的技术细节。
当前回答
令我惊讶的是,还没有人提到由类型提示引起的循环导入。 如果只有由于类型提示才有循环导入,则可以以干净的方式避免它们。
考虑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的循环导入洞中挖出来。
其他回答
模块a.py:
import b
print("This is from module a")
模块b.py
import a
print("This is from module b")
运行“Module a”将输出:
>>>
'This is from module a'
'This is from module b'
'This is from module a'
>>>
它输出了这3行,而由于循环导入,它应该输出不定式。 这里列出了运行“模块a”时逐行发生的事情:
The first line is import b. so it will visit module b The first line at module b is import a. so it will visit module a The first line at module a is import b but note that this line won't be executed again anymore, because every file in python execute an import line just for once, it does not matter where or when it is executed. so it will pass to the next line and print "This is from module a". After finish visiting whole module a from module b, we are still at module b. so the next line will print "This is from module b" Module b lines are executed completely. so we will go back to module a where we started module b. import b line have been executed already and won't be executed again. the next line will print "This is from module a" and program will be finished.
我完全同意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")
同样,这不是一个永久性的修复,但可以帮助那些希望在不修改太多代码的情况下修复导入错误的人。
干杯!
令我惊讶的是,还没有人提到由类型提示引起的循环导入。 如果只有由于类型提示才有循环导入,则可以以干净的方式避免它们。
考虑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的循环导入洞中挖出来。
我用下面的方法解决了这个问题,没有任何错误。 考虑两个文件a.py和b.py。
我把这个添加到a.py,它工作了。
if __name__ == "__main__":
main ()
a.py:
import b
y = 2
def main():
print ("a out")
print (b.x)
if __name__ == "__main__":
main ()
b.py:
import a
print ("b out")
x = 3 + a.y
得到的输出是
>>> b out
>>> a out
>>> 5
这里有很多很棒的答案。虽然通常有快速解决问题的解决方案,其中一些比其他的更python化,但如果您有能力进行一些重构,另一种方法是分析代码的组织,并尝试删除循环依赖。例如,你可能会发现:
文件a.py
from b import B
class A:
@staticmethod
def save_result(result):
print('save the result')
@staticmethod
def do_something_a_ish(param):
A.save_result(A.use_param_like_a_would(param))
@staticmethod
def do_something_related_to_b(param):
B.do_something_b_ish(param)
文件b.py
from a import A
class B:
@staticmethod
def do_something_b_ish(param):
A.save_result(B.use_param_like_b_would(param))
在这种情况下,只需要将一个静态方法移动到一个单独的文件中,例如c.py:
文件c.py
def save_result(result):
print('save the result')
将允许从A中删除save_result方法,从而允许从b中的A中删除A的导入:
重构文件a.py
from b import B
from c import save_result
class A:
@staticmethod
def do_something_a_ish(param):
save_result(A.use_param_like_a_would(param))
@staticmethod
def do_something_related_to_b(param):
B.do_something_b_ish(param)
重构文件b.py
from c import save_result
class B:
@staticmethod
def do_something_b_ish(param):
save_result(B.use_param_like_b_would(param))
总之,如果你有一个工具(例如pylint或PyCharm),它报告的方法可以是静态的,只是在它们上抛出一个staticmethod装饰器可能不是静音警告的最好方法。尽管方法看起来与类相关,但最好将其分离出来,特别是如果您有几个密切相关的模块,它们可能需要相同的功能,并且您打算实践DRY原则。