python
module_error
ai_generated
true
ImportError: 尝试相对导入,但没有已知的父包
ImportError: attempted relative import with no known parent package
ID: python/pytest-import-mismatch
80%修复率
85%置信度
0证据数
2024-09-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
测试文件使用了相对导入(例如 from . import module),但它不是包的一部分,或作为脚本运行。
English
A test file uses relative imports (e.g., from . import module) but is not part of a package, or is run as a script.
解决方案
-
90% 成功率
From the project root, run: python -m pytest tests/ This ensures the current directory is in sys.path and relative imports work if tests are part of a package.
-
95% 成功率
pip install -e . Then use absolute imports like 'from mypackage import module' in tests.
无效尝试
常见但无效的做法:
-
70% 失败
If the test is run as a top-level script, relative imports still fail because there is no parent package.
-
60% 失败
This may work but can break if the package structure changes or if the test is run from different directories.