You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决Python模块循环导入及ModuleNotFoundError问题

解决Python模块导入错误与循环依赖问题

一、修复模块找不到的报错(ModuleNotFoundError)

当前报错核心原因:Python导入labelling时,会在当前工作目录(即main.py所在的根目录)查找模块,但labelling.py实际位于src子目录下,因此无法匹配。可通过两种方式修正导入路径:

方式1:使用绝对导入

  1. 在src目录下创建空的__init__.py文件(将src标记为Python包,Python3.3+虽可不加,但添加后兼容性更好)
  2. 修改两个模块的导入语句:
    • mypandas.py替换原导入为:
      from src import labelling as l
      
    • labelling.py替换原导入为:
      from src import mypandas as myp
      

方式2:使用相对导入

直接在src内部模块间使用相对路径导入,无需额外创建文件:

  • mypandas.py替换原导入为:
    from . import labelling as l
    
  • labelling.py替换原导入为:
    from . import mypandas as myp
    

二、解决循环导入问题

修正路径后,还会遇到循环导入问题(mypandas与labelling互相导入),导致模块加载时出现AttributeError或对象未定义的错误,可通过以下两种方案解决:

方法1:延迟导入(快速解决首选)

将导入语句从模块顶部移至实际使用的函数内部,避免模块初始化阶段互相引用未加载完成的对象:
示例(mypandas.py):

# 移除顶部的import labelling语句
import pandas as pd
import plotly.express as px

def foo():
    print('oui')

def use_labelling_tool():
    # 仅在需要调用时导入
    from . import labelling as l
    l.your_labelling_function()  # 调用labelling中的目标函数

同理,labelling.py中若需调用mypandas的类,也将导入逻辑移至对应函数内部:

# 移除顶部的import mypandas语句
def process_with_mypandas():
    from . import mypandas as myp
    df_handler = myp.YourPandasClass()  # 实例化mypandas中的类

方法2:重构代码(长期维护首选)

将两个模块互相依赖的代码提取到新的公共模块,彻底避免循环依赖:

  1. 在src目录下新建common.py文件,把mypandas和labelling互相依赖的类、函数迁移至此
  2. 修改两个模块的导入逻辑,改为从common导入所需内容:
    • mypandas.py:
      from .common import required_labelling_function
      
    • labelling.py:
      from .common import required_pandas_class
      

三、验证运行

修改完成后,直接运行main.py即可,原导入语句import src.labelling as sl和import src.mypandas as sp无需调整。

内容的提问来源于stack exchange,提问作者Marc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:16:11