python module_error ai_generated true

ImportError: 尝试相对导入但没有已知的父包

ImportError: attempted relative import with no known parent package

ID: python/pytest-import-mismatch-relative

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-05-08首次发现

版本兼容性

版本状态引入弃用备注
7.x active — — —
8.x active — — —

根因分析

测试模块使用了相对导入(from .foo import bar),但测试目录缺少 __init__.py,pytest 会将测试文件作为顶层模块导入,从而失去包上下文,导致相对导入失败。

English

Test modules use relative imports (from .foo import bar) but pytest imports test files as top-level modules when no __init__.py exists in the test directory. Without the package context, relative imports fail.

generic

解决方案

  1. 92% 成功率
    touch tests/__init__.py
    touch tests/unit/__init__.py
    # then run from project root
    pytest tests/
  2. 95% 成功率
    # before: from .helpers import make_user
    # after:
    from tests.helpers import make_user
  3. 85% 成功率
    # pyproject.toml
    [tool.pytest.ini_options]
    addopts = "--import-mode=importlib"

无效尝试

常见但无效的做法:

  1. 80% 失败

    Path insertion does not create a parent package; relative imports still fail because __package__ is empty.

  2. 75% 失败

    Changes rootdir discovery but does not fix the missing package marker; the relative import still has no parent.