python
module_error
ai_generated
true
ERROR collecting docs/usage.rst E ModuleNotFoundError: No module named 'mypkg' # when running pytest --doctest-glob='*.rst'
ID: python/pytest-doctest-import-path
80%Fix Rate
85%Confidence
0Evidence
2025-07-14First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 7.x | active | — | — | — |
| 8.x | active | — | — | — |
Root Cause
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.
generic中文
在 .rst 文件中收集 doctest 时,docs 目录不在 sys.path 上,因此代码块中的导入失败,即使包已以可编辑模式安装。
Workarounds
-
92% success
Set pythonpath in pytest.ini so the package is importable from any cwd: [pytest] pythonpath = . src addopts = --doctest-glob='*.rst'
-
90% success
Or install editable before running doctests: pip install -e . && pytest --doctest-glob='*.rst' docs/
Dead Ends
Common approaches that don't work:
-
85% fail
Doctest code blocks are not executable module-level statements; the insert runs but relative to the wrong cwd.
-
75% fail
Installs a copy that may not reflect the working tree, causing stale doctest results.