症状
导入语句报 cannot import name X from Y,即便该包安装正常。它常只在模块互相导入的较大应用中浮现。
诊断
检查符号与模块来源:
import Y
print(Y.__file__)
print(hasattr(Y, 'X'))
若 __file__ 位于你的项目树内,说明导入的是本地文件;否则可能是循环导入返回了尚未完成定义的模块。
修复
用局部导入打破循环:
# a.py imports b.py, b.py imports a.py -> cycle
def handler():
from a import helper # deferred, avoids the cycle
return helper()
重命名产生遮蔽的文件,并更新被重命名的符号。
验证
执行 python -c "from Y import X",应成功;应用入口也应能正常启动而不再报 ImportError。