python
module_error
ai_generated
true
ImportError: 尝试相对导入但没有已知的父包
ImportError: attempted relative import with no known parent package
ID: python/pytest-import-mismatch-error
80%修复率
89%置信度
0证据数
2024-02-08首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
pytest 在特定配置下(例如测试目录中没有 __init__.py 或 rootdir 设置错误)默认不会将项目根目录添加到 sys.path。测试文件中的相对导入因此失败。
English
pytest does not add the project root to sys.path by default when using certain configurations (e.g., no __init__.py in test directories or using rootdir incorrectly). Relative imports in test files then fail.
解决方案
-
93% 成功率
# pytest.ini [pytest] pythonpath = . # Or in pyproject.toml: # [tool.pytest.ini_options] # pythonpath = ["."]
-
88% 成功率
pip install -e . # Then absolute imports work from anywhere
无效尝试
常见但无效的做法:
-
75% 失败
The current working directory may not be the project root when pytest is invoked from a different location. This is fragile and non-portable.
-
65% 失败
This may work locally but breaks when the package is installed or when tests are run from a different directory. It also violates package structure conventions.