【发布时间】:2026-02-09 09:20:12
【问题描述】:
我正在处理一个包含大约 30 个独特模块的项目。它设计得不太好,因此在向项目添加一些新功能时,我通常会创建循环导入。
当然,当我添加循环导入时,我并没有意识到这一点。有时很明显,当我收到AttributeError: 'module' object has no attribute 'attribute' 之类的错误时,我已经进行了循环导入,其中我明确定义了'attribute'。但其他时候,代码不会因为使用方式而引发异常。
所以,对于我的问题:
是否可以以编程方式检测循环导入发生的时间和地点?
到目前为止,我能想到的唯一解决方案是有一个模块importTracking,其中包含一个字典importingModules,一个函数importInProgress(file),它递增importingModules[file],如果大于1,则抛出错误,和一个函数importComplete(file) 递减importingModules[file]。所有其他模块如下所示:
import importTracking
importTracking.importInProgress(__file__)
#module code goes here.
importTracking.importComplete(__file__)
但这看起来真的很讨厌,一定有更好的方法来做到这一点,对吧?
【问题讨论】:
-
你怎么知道你创建了循环导入?如果你不知道,有什么问题?请具体说明问题。
标签: python circular-dependency