python
module_error
ai_generated
true
收集 docs/usage.rst 时出错 E ModuleNotFoundError: 没有名为 'mypkg' 的模块 # 运行 pytest --doctest-glob='*.rst' 时
ERROR collecting docs/usage.rst E ModuleNotFoundError: No module named 'mypkg' # when running pytest --doctest-glob='*.rst'
ID: python/pytest-doctest-import-path
80%修复率
85%置信度
0证据数
2025-07-14首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
根因分析
在 .rst 文件中收集 doctest 时,docs 目录不在 sys.path 上,因此代码块中的导入失败,即使包已以可编辑模式安装。
English
Doctests in .rst files are collected from the docs directory, which is not on sys.path, so imports inside code blocks fail even though the package is installed in editable mode.
解决方案
-
92% 成功率
Set pythonpath in pytest.ini so the package is importable from any cwd: [pytest] pythonpath = . src addopts = --doctest-glob='*.rst'
-
90% 成功率
Or install editable before running doctests: pip install -e . && pytest --doctest-glob='*.rst' docs/
无效尝试
常见但无效的做法:
-
85% 失败
Doctest code blocks are not executable module-level statements; the insert runs but relative to the wrong cwd.
-
75% 失败
Installs a copy that may not reflect the working tree, causing stale doctest results.