我想了解问题的根源。我已经遇到过几次这种情况,每次解决它都非常耗时。
这次我觉得我错过了一些我以为我理解的东西。 相关问题发布在这里:Infinite loop with Python imports; looking for Pythonic way
我确定我的模块存在无限循环,但我仍然遇到相同的错误。这就是我所拥有的。
我已经包括了__init__.py
文件也放在这里,因为我怀疑这个文件可能会导致我目前不知道的行为。
在 sources/preparation/features/__Init__.py
:
from .build_features import *
from .get_qualified_edges import *
from .select_strategy import *
from .test import *
在 sources/preprocessing/__init__.py
,我有:
from .apply_preprocessing import *
from .convertion import *
在 sources/preprocessing/apply_preprocessing
我有:
from Sources.Preparation.Features.get_qualified_edges import get_all_GeneDisease_unweighted_disease2disease_qualified_edges
from Sources.Preparation.Features.get_qualified_edges import get_GPSim_disease2disease_qualified_edgesjk
在目录source/preparation/features/get_qualified_edges.py
:
from Sources.Preprocessing.convertion import Converter # added this lien causes error to be raised
from itertools import combinations
在 Sources/preprocessing/conversion.py
我没有导入任何东西。
以下是由于出现错误而运行的文件顺序:
sources\__init__.py
sources\preparation\__init__.py
sources\prepartion\features\__init__.py
sources\preparation\features\build_features.py
sources\preparation\features\get_qualified_edgdes.py
sources\preprocessing\__init__.py
sources\preprocessing\apply_preprocessing.py
\\error raise
当我从 Sources.Preprocessing.convertion
导入类时出现错误如下所示。在 source/preparation/features/get_qualified_edges.py
:
from Sources.Preprocessing.convertion import Converter # added this lien causes error to be raised
如果你们需要有关此问题的更多信息,请告诉我。
我想知道的是:为什么会出现这个问题?
我搬家时解决了这个问题Converter
来自Sources.Preprocessing.convertion
至Sources.Preparation.Data.conversion
.
观察
我观察到,当Sources.Preprocessing.modules_A
之间没有“交叉”导入时,错误消失了。 (在 Sources.Preparation.modules_C
中导入)和 Sources.Preparation.modules_B
(在 Sources.Preprocessing.modules_D
中导入)。
就是这样。模块之间没有直接的“交叉”导入,而是父模块之间有“交叉”导入(如果这有意义的话)。
最佳答案
问题在于您正在从文件中引入循环导入。
对于 sources/preprocessing
中的文件,您将从 source/preparation
导入内容。但这些文件反过来又从 source/preprocessing
导入内容。
一旦你有了类似的导入链
A.py -> B.py -> C.py -> B.py -> E.py
(直接循环)
或
A.py -> B.py -> C.py -> D.py-> B.py -> E.py
(间接循环)
那么它将无法继续导入模块,因为它不可能终止。
在 python 中解决这个问题的一个简单方法是使用本地导入。
例如,而不是
from Sources.Preprocessing.convertion import Converter
# more code.....
class A:
def foo():
bar = Converter()
您可以使用本地导入,例如
# more code.....
class A:
def foo():
from Sources.Preprocessing.convertion import Converter
bar = Converter()
这样它仅在您实际使用该对象之前导入。这将避免在开始时导入所有内容,从而避免循环导入。
<小时/>编辑:
简而言之,回答OP关于这个特定问题的问题:
在代码中的某个位置您启动了预处理模块的导入。 (可能在 sources\preparation\features\get_qualified_edgdes.py
中?不太确定)
此时,预处理被添加到sys.modules
命名空间中,但作为一个空模块(占位符)。
稍后在同一个导入链中,在文件 source/preparation/features/get_qualified_edges.py
中,行
from Sources.Preprocessing.convertion import Converter
尝试从Preprocessing模块导入convertion
,但会发现一个空模块(因为仍在导入过程中),因此无法找到相应的模块名称(在本例中为转换
)。
关于python - 如何解决无限循环导入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60031989/