PyCharm项目中utils模块导入失败求助:无法正确导入自定义类与函数
问题梳理
你的项目目录结构如下:
myproject utils utilities myclass.py __init__.py anothermodule __init__.py src helper_func.py __init__.py venv main.py
你期望通过以下方式调用类和函数:
object = utilities.myclass.myclass(...) thing = utilities.anothermodule.src.helper_func.helper_func(...)
尝试导入语句from utils import utilities后,出现错误:
AttributeError: module 'utils.utilities' has no attribute 'myclass'
你已经将utils、utilities、anothermodule、src标记为源根,也把utils路径添加到了sys.path,但问题仍未解决。
解决方法
1. 完善__init__.py的导出逻辑
Python的包需要通过__init__.py文件对外暴露子模块或成员,默认导入父包不会自动加载所有子模块。你需要在各级__init__.py中添加导入语句:
- 在
utils/utilities/__init__.py中添加:from . import myclass from . import anothermodule - 在
utils/utilities/anothermodule/__init__.py中添加:from . import src - 在
utils/utilities/anothermodule/src/__init__.py中添加:from . import helper_func
完成后,执行from utils import utilities就能正常访问utilities.myclass.myclass和utilities.anothermodule.src.helper_func.helper_func了。
2. 直接使用精确的绝对导入
如果不想修改__init__.py,可以在main.py中直接导入目标类和函数:
from utils.utilities.myclass import myclass from utils.utilities.anothermodule.src.helper_func import helper_func object = myclass(...) thing = helper_func(...)
3. 修正源根标记
不需要将所有子文件夹都标记为源根,过多标记会导致Python路径识别混乱。建议只将myproject文件夹标记为源根(右键文件夹 → Mark Directory as → Sources Root),取消utilities、anothermodule、src的源根标记。
4. 验证sys.path是否正确
在main.py开头添加以下代码,检查当前Python路径是否包含项目根目录:
import sys from pathlib import Path print(sys.path) # 如果路径不包含myproject,手动添加 sys.path.append(str(Path(__file__).parent))
内容的提问来源于stack exchange,提问作者cercio
相关产品推荐
相关产品推荐

