python module_error ai_generated true

ImportError: attempted relative import with no known parent package

ID: python/pytest-import-mismatch-relative

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-05-08First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
7.x active — — —
8.x active — — —

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 75% fail

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